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]
Code:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 |
class
Solution {public: void
findSum(vector<int> &S,int
sum,int
level,int
&t,vector<int> &buf,vector<vector<int>> &res){ for(int
i=level;i<S.size();i++){ buf.push_back(S[i]); if(sum+S[i]==t) res.push_back(buf); if(sum+S[i]<=t) findSum(S,sum+S[i],i,t,buf,res); buf.pop_back(); } } vector<vector<int> > combinationSum(vector<int> &candidates, int
target) { vector<int> buf; vector<vector<int>> res; sort(candidates.begin(),candidates.end()); findSum(candidates,0,0,target,buf,res); return
res; }}; |
原文:http://www.cnblogs.com/winscoder/p/3535467.html