Combination Sum
Medium
Topics
Given distinct positive integers candidates and a target, return all unique combinations that sum to target. A candidate may be reused unlimited times.
Example 1
Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]]
Example 2
Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]]
Constraints
- 1 <= candidates.length <= 30
- All candidates are distinct positive integers.
- 1 <= target <= 40
Editorial — intuition, approach, complexity and pitfalls
Intuition
Explore combinations by choosing candidates in non-decreasing index order (so each combination is generated once), subtracting from the remaining target and allowing reuse of the current index.
Approach
- DFS with (start index, remaining).
- When remaining hits 0, record the path; if it goes negative, prune.
- Recurse with the same index i (reuse) to allow repeats.
Dry Run
candidates [2, 3, 6, 7] (sorted), target 7
`rem` counts down; reaching exactly 0 records the path.
take 2 rem 5 path [2] recurse from i=0, so 2 may repeat
take 2 rem 3 path [2,2] recurse from i=0
take 2 rem 1 path [2,2,2]
2 > rem 1 -- sorted, so every later candidate is too: BREAK
take 3 rem 0 path [2,2,3] -> record
6 > rem 3: BREAK
take 3 rem 2 path [2,3]
3 > rem 2: BREAK
6 > rem 5: BREAK
take 3 rem 4 path [3]
take 3 rem 1 path [3,3]
3 > rem 1: BREAK
6 > rem 4: BREAK
take 6 rem 1 path [6]
6 > rem 1: BREAK
take 7 rem 0 path [7] -> record
answer [2, 2, 3] and [7]
Two uses of the sort, doing different jobs. `break` rather than `continue` is
valid only because the candidates ascend -- once one exceeds rem, so does every
candidate after it, which prunes the whole tail in one step. And recursing from
`i` rather than `i + 1` is what permits reuse: [2,2,3] needs the 2 twice. The
start index never moving backwards is separately what stops [3,2,2] being emitted
as a second copy of the same multiset.
Pass i + 1 instead and reuse is forbidden: the answer drops to just [[7]], since
no single-use subset of [2,3,6] sums to 7.Complexity
- Time — O(2^t): exponential in target/candidate ratio; pruned by the break.
- Space — O(target): recursion depth.
Common Pitfalls
- Recurse with i (not i+1) to permit reuse; pass i+1 and you forbid repeats.
Full Solution — all languages
class Solution:
def combinationSum(self, candidates, target):
candidates.sort()
res=[]
def dfs(start,rem,path):
if rem==0: res.append(path[:]); return
for i in range(start,len(candidates)):
if candidates[i]>rem: break
path.append(candidates[i]); dfs(i,rem-candidates[i],path); path.pop()
dfs(0,target,[])
return resimport java.util.*;
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res=new ArrayList<>();
dfs(candidates,0,target,new ArrayList<>(),res);
return res;
}
void dfs(int[] c,int start,int rem,List<Integer> path,List<List<Integer>> res) {
if(rem==0) {
res.add(new ArrayList<>(path));
return;
}
for(int i=start;i<c.length;i++) {
if(c[i]>rem)break;
path.add(c[i]);
dfs(c,i,rem-c[i],path,res);
path.remove(path.size()-1);
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> res;
vector<int> path;
function<void(int,int)> dfs=[&](int start,int rem) {
if(rem==0) {
res.push_back(path);
return;
}
for(int i=start;i<(int)candidates.size();i++) {
if(candidates[i]>rem)break;
path.push_back(candidates[i]);
dfs(i,rem-candidates[i]);
path.pop_back();
}
};
dfs(0,target);
return res;
}
};/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/ var combinationSum = function(candidates, target) {
candidates.sort((a,b)=>a-b);
const res=[];
function dfs(start,rem,path) {
if(rem===0) {
res.push(path.slice());
return;
}
for(let i=start;i<candidates.length;i++) {
if(candidates[i]>rem)break;
path.push(candidates[i]);
dfs(i,rem-candidates[i],path);
path.pop();
}
}
dfs(0,target,[]);
return res;
};