generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.cpp
40 lines (35 loc) · 1.07 KB
/
solution.cpp
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
39
40
#include <algorithm>
#include <span>
#include <vector>
class Solution {
public:
std::vector<std::vector<int>> combinationSum2(
std::vector<int>& candidates, int target) {
std::sort(candidates.begin(), candidates.end());
std::vector<std::vector<int>> combinations{};
std::vector<int> current{};
fillCombinations(combinations, current, candidates, target);
return combinations;
}
void fillCombinations(
std::vector<std::vector<int>>& combinations,
std::vector<int>& current,
std::span<int> candidates,
int target) {
int prevCandidate{0};
for (std::size_t i{0}; i < candidates.size(); ++i) {
if (candidates[i] > target) break;
if (candidates[i] == prevCandidate) continue;
prevCandidate = candidates[i];
current.push_back(candidates[i]);
if (candidates[i] == target) {
combinations.push_back(current);
} else {
fillCombinations(
combinations, current, candidates.subspan(i + 1),
target - candidates[i]);
}
current.pop_back();
}
}
};