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:
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is:
[7]
[2, 2, 3]
本题最大的特点就是允许重复值出现进行累加。
这个题并没有限制solution Set的大小,所以应该是用DFS了。才开始想到了取一个数candidate[i]后,目标变为target-candiadate[i]。但是i想着需要逆向,从大到小去取值。为了逆向去找最大值的小标i,很费劲,代码很复杂,调试了很久。最后还是需要绕回到从正向由小到大去取。因为可以取重复值,所以递归的下标并没有变化,从原地开始(体现在代码21行的i上)。
class Solution { public: vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<vector<int> > ret; vector<int> solve; sort(candidates.begin(),candidates.end()); DFS(candidates,solve,ret,0,target); return ret; } private: void DFS(vector<int> &candidates,vector<int> &solve, vector<vector<int> > &ret,int start,int target){ if(target==0){ ret.push_back(solve); return; } for(size_t i=start;i<candidates.size();i++){ if(candidates[i]>target)return; //剪枝 solve.push_back(candidates[i]); DFS(candidates,solve,ret,i,target-candidates[i]); solve.pop_back(); } } };
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
For example, given candidate set 10,1,2,7,6,1,5
and target 8
,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
class Solution { public: vector<vector<int> > combinationSum2(vector<int> &candidates, int target) { set<vector<int> > ret; vector<int> solve; sort(candidates.begin(),candidates.end()); DFS(candidates,solve,ret,0,target); int n=ret.size(); vector<vector<int> > result(n); std::copy(ret.begin(),ret.end(),result.begin()); return result; } private: void DFS(vector<int> &candidates,vector<int> &solve, set<vector<int> > &ret,int start,int target){ if(target==0){ ret.insert(solve); return; } for(size_t i=start;i<candidates.size();i++){ if(candidates[i]>target)return; //剪枝 solve.push_back(candidates[i]); DFS(candidates,solve,ret,i+1,target-candidates[i]); solve.pop_back(); } } };