39. 组合总和
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]
]
回溯法
这里用的减的方法做的,每次取出的数字如果符合条件,就用target减掉,当target为0时,就产生一种组合了,产生的这种组合用一个vector数组保存,然后在加到vector<vector>数组中。当target小于0了,直接返回。这道题允许重复使用数字,但不允许有重复的集合,比如{2,3,3},{3,2,3}这就是算重复的。所以在循环时,初始值不应该从下标0开始,而是从上一次递归的下标开始。这里需要注意,否则最后结果将是有重复的集合。
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> vec;
vector<int> v; //保存产生组合的数字
dfs(candidates,target,vec,v,0);
return vec;
}
void dfs(vector<int>& candidates,int target,vector<vector<int>>& vec,vector<int> &v,int k)
{
if(target<0) return;
if(target == 0)
{
vec.push_back(v);
return;
}
for(int i=k;i<candidates.size();i++)
{
int r=candidates[i];
//if(target<r) continue;
v.push_back(r);
dfs(candidates,target-r,vec,v,i); //注意i值
v.pop_back();
}
}
};