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> res;
vector tmp;
vector> combinationSum(vector& candidates, int target) {
int n = candidates.size();
helper(candidates, target, 0, n);
return res;
}
void helper(vector& 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> combinationSum(vector& candidates, int target) {
vector> res;
vector tmp;
sort(candidates.begin(), candidates.end());
backtrack(candidates, res, tmp, target, 0);
return res;
}
void backtrack(vector candidates, vector>& res, vector& tmp, int target, int begin) {
if(target == 0)
res.push_back(tmp);
else{
for(int i = begin; i= candidates[i]; i++){
tmp.push_back(candidates[i]);
backtrack(candidates, res, tmp, target-candidates[i], i);
tmp.pop_back();
}
}
}
通过初始排序和剪枝加快了回溯的速度。
几个经典的回溯法题解:
https://leetcode.com/problems/combination-sum/discuss/16502/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partitioning)