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 is chosen from 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 set and 2,3,6,7
target 7
,
A Solution set is:
[7]
[2, 2, 3]
classSolution { Public: voidGetcombinationsum (intcurrentsum,vector<int>& candidates,intIndex,vector <vector<int>> &solution, Vector <int> &result,inttarget) { if(Currentsum = = target) {//if and equal to the target, press the result into the solution and return to the previous layersolution.push_back (Result); return; } Else{//if and less than the target, you can continue to join the value for(inti = index; I < candidates.size (); i++) {currentsum+=Candidates[i]; if(currentsum> target) {//when the value is greater than the target, the queue cannot be compounded again, and the loop is directlyCurrentsum-=Candidates[i]; Break; } result.push_back (Candidates[i]);//press the current result to continue the recursive callgetcombinationsum (Currentsum,candidates,i,solution,result,target); Currentsum-= Candidates[i];//returns a description of the condition before a solution is found, so the last press-in is removed, and then the new value is added to the loopResult.pop_back (); }}} vector<vector<int>> Combinationsum (vector<int>& candidates,inttarget) {Vector<vector<int>>solution; Vector<int>result; intCurrentsum =0; Sort (Candidates.begin (), Candidates.end ());//sort the inputs first to make sure the output is orderlyGetcombinationsum (Currentsum,candidates,0, Solution,result,target); returnsolution; }};
Leetcode 39. Combination Sum