Problem description

Combination Sum

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,

1
2
3
4
5
A solution set is:
[
[7],
[2,2,3]
]

Example 2:

1
2
3
4
5
6
7
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

Solution

先对 candidates 进行排序。从初始开始选定一个。如果选定一个 candidates[i],则需要继续寻找和为 target-candidate[i]combination。由于 candidatestarget 都为正数,当和超过或等于target 时,查找中止。与 3sum 的思路一样,对 candidates 排序,并且每层递归扫描的时候需要做到去重复解:

  1. 不回头扫,在扫描 candidates[i] 时,对 candidate[i: n-1] 递归查找target-candidates[i]

  2. 每层扫描的时候跳过重复的 candidates

  3. 每个 candidate 可以重复好几次,所以在递归调用中,findComSum(candidates, i, target - candidates[i], one, res);i 开始。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
vector< vector<int> > combinationSum(vector<int>& candidates, int target) {
vector < vector <int> > res;
vector <int> one;
if(candidates.empty())
return res;
sort(candidates.begin(),candidates.end()); // sort candidates
findComSum(candidates, 0, target, one, res);
return res;
}
void findComSum(vector<int> &candidates, int start, int target, vector<int> &one, vector< vector<int> >&res){
if(target == 0){
res.push_back(one);
return;
}
for(int i = start; i < candidates.size(); i++){
if(i > start && candidates[i] == candidates[i-1])
continue;
if(candidates[i] <= target){
one.push_back(candidates[i]);
findComSum(candidates, i, target - candidates[i], one, res);
one.pop_back();
}
}
}
};