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 {
vector<vector<int> > ret;
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
int size = num.size();
if(size == 0) return vector<vector<int> >();
sort(num.begin(), num.end());
//DFS求解
vector<int> item;
vector<bool> used(size, false);
DFS(num, 0, used, item, target);
return ret;
}
void DFS(vector<int> &candidates, int level, vector<bool> &used, vector<int> &item, int target) {
if(target < 0){
return ;
} else if(target == 0) {
ret.push_back(item);
return ;
} else {
if(level == candidates.size()) return;
//先剪枝
if(level > 0 && candidates[level] == candidates[level - 1] && used[level - 1] == false) {
DFS(candidates, level + 1, used, item, target);
return;
}
//选
used[level] = true;
item.push_back(candidates[level]);
DFS(candidates, level + 1, used, item, target - candidates[level]);
//不选
used[level] = false;
item.pop_back();
DFS(candidates, level + 1, used, item, target);
}
}
};