generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.cpp
33 lines (30 loc) · 901 Bytes
/
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
#include <span>
#include <vector>
class Solution {
public:
std::vector<std::vector<int>> combinationSum(
std::vector<int>& candidates, int target) {
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) {
for (std::size_t i{0}; i < candidates.size(); ++i) {
if (candidates[i] > target) continue;
current.push_back(candidates[i]);
if (candidates[i] == target) {
combinations.push_back(current);
} else {
fillCombinations(
combinations, current, candidates.subspan(i),
target - candidates[i]);
}
current.pop_back();
}
}
};