Given a collection of candidate numbers (C) And a target number (T), Find all unique combinations inCWhere the candidate numbers sumsT.
Each number inCMay only be used once in the combination.
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, 5 and Target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Idea: sort the input data first, and then use DFS. Because each element appears only once, to avoid repetition, recursive calling should start with the next element that is larger than the current element.
1 class Solution { 2 public: 3 vector<vector<int> > combinationSum2( vector<int> &num, int target ) { 4 vector<int> combination; 5 sort( num.begin(), num.end() ); 6 vector<int>::iterator begin = num.begin(), end = num.end(); 7 CombinationSub( combination, begin, end, target ); 8 return combinations; 9 }10 private:11 void CombinationSub( vector<int> combination, vector<int>::iterator &begin, vector<int>::iterator &end, int target ) {12 if( begin == end || target < *begin ) { return; }13 vector<int>::iterator next = upper_bound( begin, end, *begin );14 CombinationSub( combination, next, end, target );15 for( int i = 0; begin+i != next && target >= *begin; ++i ) {16 target -= *begin;17 combination.push_back( *begin );18 if( target == 0 ) { combinations.push_back( combination ); break; }19 CombinationSub( combination, next, end, target );20 }21 return;22 }23 vector<vector<int>> combinations;24 };
Combination sum II