1,题目要求
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]
]
给定一组候选数字(candidates)(没有重复)和目标数字(target),找到候选人数总和目标的候选人中的所有独特组合。
可以从候选者无限次数中选择相同的重复数字。
2,题目思路
对于这道题,是给定一系列的候选数字,然后再给出一个数字目标,找出所有从候选数字内选出的数字之和等于目标的结果集合。
在求解时, 我们使用回溯的办法来求解这道题。
看到算法的实现和之前Permutations的实现非常类似,于是想到回溯和递归的区别到底是什么。
之后在查找出资料后,专门写一篇博客探讨这个问题。
3,代码实现
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> res;
vector<int> tmpRes;
backTracking(candidates, target, res, tmpRes, 0);
return res;
}
private:
void backTracking(vector<int> &candidates, int target, vector<vector<int>> &res, vector<int> &tmpRes, int begin){
//tmpRes满足给定的target条件
if(target == 0){
res.push_back(tmpRes);
return;
}
//target>=candidates[i]是一种减枝的功能
for(int i = begin;i<candidates.size() && target>=candidates[i];i++){
tmpRes.push_back(candidates[i]);;
backTracking(candidates, target-candidates[i], res, tmpRes, i);
tmpRes.pop_back(); //恢复
}
}
};