39. Combination Sum
- Total Accepted: 102477
- Total Submissions: 316416
- Difficulty: Medium
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.
- 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] ]
思路:回溯法遍历元素,满足条件就返回。
代码:
1 class Solution { 2 public: 3 vector<vector<int>> res; 4 void combinationSum(vector<int>& v,vector<int>& candidates,int target,int cur){ 5 if(target==0){ 6 res.push_back(v); 7 return; 8 } 9 int i,n=candidates.size(); 10 for(i=cur;i<n;i++){ 11 target-=candidates[i]; 12 if(target>=0){ 13 v.push_back(candidates[i]); 14 combinationSum(v,candidates,target,i); 15 v.pop_back(); 16 } 17 else{//剪枝 18 return; 19 } 20 target+=candidates[i]; 21 } 22 } 23 vector<vector<int>> combinationSum(vector<int>& candidates, int target) { 24 sort(candidates.begin(),candidates.end()); 25 vector<int> v; 26 combinationSum(v,candidates,target,0); 27 return res; 28 } 29 };