Given a set of candidate numbers (C) and a target number (T), find all unique combinations in c< /c5> where the candidate numbers sums to T.
the&NBSP; same Repeated number may be chosen From&NBSP; C unlimited number of times.
Note:
- All numbers (including target) would be positive integers.
- Elements in a combination (a1, a 2, ..., ak) must is in non-descending order. (ie, a1 ≤ a2 ≤ ... ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set2,3,6,7
and target 7
, &NBSP;
A solution set Is: [7]
&NBSP;
[2, 2, 3]
&NBSP;
Use the Backtracking method:
1 classSolution {2 Public:3 voidBackTrace (vector<int>& candidates,intSumintTarget, vector<vector<int> > &results,vector<int> &result,intindex)4 {5 if(Sum = =target)6 {7 results.push_back (result);8 return;9 }Ten Else if(Sum >target) One { A return; - } - Else if(Sum <target) the { - for(inti = index; I < candidates.size (); + +i) - { - Result.push_back (Candidates[i]); +BackTrace (candidates, sum +candidates[i],target,results,result,i); - Result.pop_back (); + } A } at - } -vector<vector<int>> Combinationsum (vector<int>& candidates,inttarget) { - sort (Candidates.begin (), Candidates.end ()); -vector<vector<int> >results; -vector<int>result; in intindex =0; - intsum =0; to + BackTrace (candidates,sum,target,results,result,index); - the returnresults; * } $};
(Leetcode) Combination Sum