-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombination-sum-ii.h
61 lines (53 loc) · 1.75 KB
/
combination-sum-ii.h
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#ifndef COMBINATION_SUM_II_H_
#define COMBINATION_SUM_II_H_
#include <algorithm>
#include <numeric>
#include <unordered_map>
#include <vector>
namespace solution {
std::vector<std::vector<int>> combinationSum2(
std::vector<int>& candidates, int target, int offset,
std::unordered_map<int, std::vector<std::vector<int>>>&
memo) {
if (offset == candidates.size() || target < 0 ||
std::accumulate(candidates.begin() + offset, candidates.end(), 0) <
target)
return {};
auto key = (target << 8) + offset + 1;
if (memo.count(key) == 0) {
memo[key] = combinationSum2(candidates, target, offset + 1, memo);
}
auto first{memo[key]};
if (candidates[offset] <= target) {
key = ((target - candidates[offset]) << 8) + offset + 1;
if (memo.count(key) == 0) {
memo[key] = combinationSum2(candidates, target - candidates[offset],
offset + 1, memo);
}
auto second{memo[key]};
if (second.empty()) {
if (candidates[offset] == target) {
second.push_back({target});
}
} else {
for (auto& v : second) {
v.push_back(candidates[offset]);
}
}
first.insert(first.end(), second.begin(), second.end());
}
return first;
}
std::vector<std::vector<int>> combinationSum2(std::vector<int>& candidates,
int target) {
std::unordered_map<int, std::vector<std::vector<int>>> memo;
auto result = combinationSum2(candidates, target, 0, memo);
for (auto& v : result) {
std::sort(v.begin(), v.end());
}
std::sort(result.begin(), result.end());
result.erase(std::unique(result.begin(), result.end()), result.end());
return result;
}
} // namespace solution
#endif // !COMBINATION_SUM_II_H_