标签:des style blog color os io 使用 strong ar
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 may only be used once in the combination.
Note:
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
思路:先对输入数据进行排序,然后使用DFS即可。因为每个元素只出现一次,为了避免重复,递归调用应从下一个比当前元素大的元素开始。
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 };
标签:des style blog color os io 使用 strong ar
原文地址:http://www.cnblogs.com/moderate-fish/p/3950102.html