40. Combination Sum II (Medium)
Given a set of candidate numbers (C) (without duplicates) 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.
- 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]
]
Solution: DFS
class Solution {
void dfs(vector<int>& candidates, int target, vector<int>& out, int pos, vector<vector<int>>& res) {
if (target == 0) {
res.push_back(out);
return;
}
for (int i = pos; i < candidates.size() && candidates[i] <= target; ++i) {
if (i > pos && candidates[i] == candidates[i-1]) continue;
out.push_back(candidates[i]);
dfs(candidates, target-candidates[i], out, i+1, res);
out.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> out;
sort(candidates.begin(), candidates.end());
dfs(candidates, target, out, 0, res);
return res;
}
};