Combination Sum II
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
A solution set is:
10,1,2,7,6,1,5
and target 8
,A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
思路:
跟Combination Sum相似,只需要考虑去除重复的情况。当一个数字第一次被使用后,便可以得到符合要求的且包含此数的所有结果,当第二次遇到使用过的数字时,看位置是否与第一次使用时的位置一样,如果一样就跳过,以此类推。
如使用第一个1,便可得到
[1, 1, 6],[1, 2, 5],[1, 7]这三个结果。其中,[1, 1, 6]中,两个1所处的位置不同。回溯遇到第二个1时,temp中的位置为0,则与第一次使用时的位置重合,跳过。
1 class Solution 2 { 3 public: 4 void generateCombination(vector<vector<int> > &ret, vector<int> &candidates, vector<int> &temp, int target, int index) 5 { 6 if(target == 0) 7 { 8 ret.push_back(temp); 9 return; 10 } 11 12 for(int i=index; i<candidates.size(); i++) 13 { 14 if(candidates[i] <= target) 15 { 16 temp.push_back(candidates[i]); 17 generateCombination(ret, candidates, temp, target-candidates[i], i+1); 18 temp.pop_back(); 19 20 while(i+1 < candidates.size() && candidates[i] == candidates[i+1]) i++; 21 } 22 else 23 return; 24 } 25 } 26 vector<vector<int> > combinationSum2(vector<int> &candidates, int target) 27 { 28 vector<vector<int> > ret; 29 vector<int> temp; 30 31 sort(candidates.begin(), candidates.end()); 32 generateCombination(ret, candidates, temp, target, 0); 33 34 return ret; 35 } 36 };