Leetcode 40. Combination Sum II (Medium) (cpp)
Tag: Array, Backtracking
Difficulty: Medium
/*
40. Combination Sum II (Medium)
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.
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) {
vector<vector<int>> res;
vector<int> res_sub;
sort(candidates.begin(), candidates.end());
match(candidates, target, 0, res_sub, res);
return res;
}
void match(vector<int>& candidates, int target, int start, vector<int>& res_sub, vector<vector<int>>& res) {
if (target == 0) {
res.push_back(res_sub);
return;
}
for (int i = start; i < candidates.size() && candidates[i] <= target; i++) {
if (i > start && candidates[i] == candidates[i- 1]) continue;
res_sub.push_back(candidates[i]);
match(candidates, target - candidates[i], i + 1, res_sub, res);
res_sub.pop_back();
}
}
};