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:
- 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 10,1,2,7,6,1,5
and target 8
,
A solution set is: [1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
思路
在上一题基础上增加判断,如果一个数不选择,那么之后所有相同的数字也都不选择。这组题类似subsets那一组。
1 void search(vector<vector<int> > &result, vector<int> &tmp, vector<int> &candidates, int index, int target){ 2 int n = candidates.size(); 3 if(target == 0){ 4 if(((index < n && (!tmp.empty() && candidates[index] != *(tmp.end()-1)))) || index >= n) 5 result.push_back(tmp); 6 return; 7 } 8 if(index >= n) 9 return; 10 if(target < candidates[index]) 11 return; 12 if(tmp.empty() || (!tmp.empty() && *(tmp.end()-1) != candidates[index])) 13 search(result, tmp, candidates, index+1, target); 14 tmp.push_back(candidates[index]); 15 search(result, tmp, candidates, index+1, target-candidates[index]); 16 tmp.erase(tmp.end()-1); 17 } 18 vector<vector<int> > combinationSum2(vector<int> &candidates, int target) { 19 // Start typing your C/C++ solution below 20 // DO NOT write int main() function 21 vector<vector<int> > result; 22 vector<int> tmp; 23 sort(candidates.begin(), candidates.end()); 24 search(result, tmp, candidates, 0, target); 25 return result; 26 }