Given a set of candidate numbers (C) and a target number (T), find all
unique combinations in C where the candidate numbers sums to T.The same repeated number may be chosen from C unlimited number of
times.Note: All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending
order. (ie, a1 ≤ a2 ≤ … ≤ ak). The solution set must not contain
duplicate combinations. For example, given candidate set 2,3,6,7 and
target 7,
A solution set is: [7]
[2, 2, 3]
问题的关键是全解的全体,用dp的方法求解的数量比较方便,这个是用dfs的方法
因为不能有重复的出现即1 2 3 3 和 1 3 2 3是相同的
所以1、candidates要先排好序
2、是用index,记录当前递归使用的起点
加入cand[index]后,如果相等,将解加入vv;如果大于,则退出,返回上一层,说明index这个候选值太大了,index+1(实际上也会大的)。
方法的优点是思路比较简单,缺点是递归,速度较慢。
class Solution {
public:
void comb(vector<int> candidates, int index, int sum, int target, vector<vector<int>> &vv, vector<int> &path){
if(sum>target) return;
if(sum==target) {vv.push_back(path); return;}
for(int i = index; i<candidates.size(); ++i){
path.push_back(candidates[i]);
comb(candidates,i,sum+candidates[i],target,vv,path);
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> vv;
vector<int> path;
comb(candidates,0,0,target,vv,path);
return vv;
}
};
应该还有DP的变种可以做
class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector< vector< vector<int> > > combinations(target + 1, vector<vector<int>>());
combinations[0].push_back(vector<int>());
for (auto& score : candidates)
for (int j = score; j <= target; j++)
if (combinations[j - score].size() > 0) {
auto tmp = combinations[j - score];
for (auto& s : tmp)
s.push_back(score);
combinations[j].insert(combinations[j].end(), tmp.begin(), tmp.end());
}
auto ret = combinations[target];
for (int i = 0; i < ret.size(); i++)
sort(ret[i].begin(), ret[i].end());
return ret;
}
};