| 1 |
class Solution { |
| 2 |
public: |
| 3 |
vector<vector<int> > combinationSum(vector<int> &candidates, int target) { |
| 4 |
// Start typing your C/C++ solution below |
| 5 |
// DO NOT write int main() function |
| 6 |
vector<int>cur; |
| 7 |
vector<vector<int>>result; |
| 8 |
int sum=0; |
| 9 |
sort(candidates.begin(),candidates.end()); |
| 10 |
myCombinationSum(candidates,cur,result,sum,0,target); |
| 11 |
|
| 12 |
return result; |
| 13 |
|
| 14 |
} |
| 15 |
|
| 16 |
void myCombinationSum(vector<int> &candidates,vector<int>&cur,vector<vector<int>>&result,int &curSum,int start,int target) |
| 17 |
{ |
| 18 |
if(start>=candidates.size())return ; |
| 19 |
for(int i=start;i<candidates.size();++i) |
| 20 |
{ |
| 21 |
curSum+=candidates[i]; |
| 22 |
cur.push_back(candidates[i]); |
| 23 |
if(curSum==target) |
| 24 |
{//搜索到了满足要求的一条路径,那么按照之前的路径继续下移或右移肯定得不到另外满足的路径,因此只能上移 |
| 25 |
result.push_back(cur);curSum-=candidates[i]; |
| 26 |
cur.pop_back();break; |
| 27 |
} |
| 28 |
else |
| 29 |
if(curSum<target) |
| 30 |
{ |
| 31 |
myCombinationSum(candidates,cur,result,curSum,i,target); |
| 32 |
curSum-=candidates[i]; |
| 33 |
cur.pop_back(); |
| 34 |
} |
| 35 |
else |
| 36 |
{ |
| 37 |
curSum-=candidates[i]; |
| 38 |
cur.pop_back(); |
| 39 |
break; |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
} |
| 44 |
}; |