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 10,1,2,7,6,1,5
and target 8
,
A solution set is: [1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
要考虑去重
每次都从当前位置选取元素,遇到重复的直接跳过就可以了
class Solution { public: vector<vector<int> > combinationSum2(vector<int> &candidates, int target) { sort(candidates.begin(),candidates.end()); vector<vector<int> > result; vector<int> tmp; backtracking(result,candidates,target,tmp,,); return result; } void backtracking(vector<vector<int> > &result,vector<int> &candidates, int &target,vector<int> tmp, int sum,int index) { if(sum==target) { result.push_back(tmp); return; } else { int sum0=sum; for(int i=index;i<candidates.size();i++) { if(i>index&&candidates[i]==candidates[i-]) { continue; } tmp.push_back(candidates[i]); sum=sum0+candidates[i]; if(sum>target) { break; }
backtracking(result,candidates,target,tmp,sum,i+); tmp.pop_back(); } } }