Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums toT.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- 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] ]
Each number in C may only be used once in the combination.
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int>tmp;
dfs(candidates, target, tmp, 0);
return s;
}
private:
void dfs(vector<int>& candidates, int target, vector<int>&tmp,int cur){
if (target < 0) return;
if (target==0){
s.push_back(tmp);
return;
}
for (int i = cur; i < candidates.size(); i++){
if (cur != i&&candidates[i] == candidates[i-1]) continue;//i-1,i
tmp.push_back(candidates[i]);
dfs(candidates, target-candidates[i], tmp,i+1);
tmp.pop_back();
}
}
vector<vector<int> > s;
};