-
Notifications
You must be signed in to change notification settings - Fork 1
/
0039.cpp
41 lines (33 loc) · 1.01 KB
/
0039.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
41
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
unordered_map<int, set<multiset<int>>> dp;
sort(candidates.begin(), candidates.end());
dp[0].insert({{}});
for (int i = 0; i < target; i++)
{
for (const auto& base : dp[i])
{
auto sum = 0;
for (auto x : base)
sum += x;
int prev = -1;
for (auto x : candidates)
{
if (sum + x > target)
break;
if (x == prev)
continue;
prev = x;
auto next = base;
next.insert(x);
dp[sum + x].insert(next);
}
}
}
vector<vector<int>> result;
for (auto& base : dp[target])
result.push_back({base.begin(), base.end()});
return result;
}
};