-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc_0040.cpp
More file actions
38 lines (36 loc) · 991 Bytes
/
lc_0040.cpp
File metadata and controls
38 lines (36 loc) · 991 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* @file lc_0040.cpp
* @brief https://leetcode-cn.com/problems/combination-sum-ii/
* @author YongDu
* @date 2021-10-04
*/
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int> &candidates, int target) {
std::sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0, 0);
return result;
}
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int> &candidates, int targetSum, int curSum, int beginIdx) {
if (curSum > targetSum) {
return;
}
if (curSum == targetSum) {
result.emplace_back(path);
return;
}
for (int i = beginIdx; i < candidates.size(); ++i) {
if (i > beginIdx && candidates[i] == candidates[i - 1]) {
continue;
}
curSum += candidates[i];
path.emplace_back(candidates[i]);
backtracking(candidates, targetSum, curSum, i + 1);
path.pop_back();
curSum -= candidates[i];
}
}
};