(leetcode) Combination Sum
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]
使用回溯法:
1 class Solution { 2 public: 3 void backtrace(vector<int>& candidates,int sum,int target, vector<vector<int > > &results,vector<int> &result,int index) 4 { 5 if(sum == target) 6 { 7 results.push_back(result); 8 return; 9 } 10 else if(sum > target) 11 { 12 return; 13 } 14 else if(sum < target) 15 { 16 for(int i = index; i < candidates.size();++i) 17 { 18 result.push_back(candidates[i]); 19 backtrace(candidates, sum + candidates[i],target,results,result,i); 20 result.pop_back(); 21 } 22 } 23 24 } 25 vector<vector<int>> combinationSum(vector<int>& candidates, int target) { 26 sort(candidates.begin(),candidates.end()); 27 vector<vector<int > > results; 28 vector<int> result; 29 int index = 0; 30 int sum = 0; 31 32 backtrace(candidates,sum,target,results,result,index); 33 34 return results; 35 } 36 };

浙公网安备 33010602011771号