[LeetCode] Combination Sum II

40. Combination Sum II

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& c, int target) {
sort(c.begin(), c.end());
vector<vector<int>> res;
vector<int> tmp;
dfs(res,tmp,c,target,0);
return res;
}

void dfs(vector<vector<int>>& res, vector<int>& tmp, vector<int>& c, int t, int st) {
if(!t) {
res.push_back(tmp);
return;
}
for(int i = st; i < c.size() and c[i] <= t; i++) {
if(i == st || c[i] != c[i-1]) {
tmp.push_back(c[i]);
dfs(res, tmp, c, t - c[i], i+1);
tmp.pop_back();
}
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/07/PS/LeetCode/combination-sum-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.