Given A collection of candidate numbers (C) and a target number (T), find all unique combinations in c where the candidate numbers sums to T.
Each number in C is used once in the combination.
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 10,1,2,7,6,1,5
target 8
,
A Solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
This problem with the previous combination Sum combination of the essence of no difference, only need to change a little bit, before the question given the array of numbers can be reused, and this problem can not be reused, just need to modify two places on the basis of the previous, first in the recursive for loop plus if (i > Start && num[i] = = Num[i-1]) continue; This prevents duplicates from appearing in the res, and then replaces the parameters in the recursive call Combinationsum2dfs with i+1, so that the numbers in the array are not reused, and the code is as follows:
classSolution { Public: Vector<vector<int> > CombinationSum2 (vector<int> &num,inttarget) {Vector<vector<int> >Res; Vector<int> out; Sort (Num.begin (), Num.end ()); Combinationsum2dfs (num, Target,0, out, RES); returnRes; } voidCombinationsum2dfs (vector<int> &num,intTargetintStart, vector<int> & out, vector<vector<int> > &Res) { if(Target <0)return; Else if(target = =0) Res.push_back ( out); Else { for(inti = start; I < num.size (); ++i) {if(i > Start && num[i] = = Num[i-1])Continue; out. Push_back (Num[i]); Combinationsum2dfs (num, Target-Num[i], i +1, out, RES); out. Pop_back (); } } }};
[Leetcode] Combination Sum II combination