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,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
解法一:
vector<vector<int>> res;
vector<int> tmp;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int n = candidates.size();
helper(candidates, target, 0, n);
return res;
}
void helper(vector<int>& candidates, int target, int index, int n) {
if(target == 0){
res.push_back(tmp);
return;
}
if(index == n) return;
helper(candidates, target, index+1, n);
for(int i = 1; i<=target/candidates[index]; i++){
tmp.push_back(candidates[index]);
helper(candidates, target-i*candidates[index], index+1, n);
}
for(int i = 1; i<=target/candidates[index]; i++)
tmp.pop_back();
}
解法二:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> tmp;
sort(candidates.begin(), candidates.end());
backtrack(candidates, res, tmp, target, 0);
return res;
}
void backtrack(vector<int> candidates, vector<vector<int>>& res, vector<int>& tmp, int target, int begin) {
if(target == 0)
res.push_back(tmp);
else{
for(int i = begin; i<candidates.size() && target >= candidates[i]; i++){
tmp.push_back(candidates[i]);
backtrack(candidates, res, tmp, target-candidates[i], i);
tmp.pop_back();
}
}
}
通过初始排序和剪枝加快了回溯的速度。