-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathobzva.cpp
43 lines (34 loc) · 1.13 KB
/
obzva.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
42
43
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
queue<pair<int, pair<int, vector<int>>>> q; // {acc, {idx, combination}}
for (int i = 0; i < candidates.size(); i++) {
int num = candidates[i];
if (num <= target) {
vector<int> comb;
comb.push_back(num);
q.push({num, {i, comb}});
}
}
while (!q.empty()) {
auto p = q.front();
q.pop();
int acc = p.first, idx = p.second.first;
auto comb = p.second.second;
if (acc == target) {
res.push_back(comb);
} else if (acc < target) {
for (int i = idx; i < candidates.size(); i++) {
int num = candidates[i];
if (acc + num <= target) {
vector<int> new_comb(comb);
new_comb.push_back(num);
q.push({acc + num, {i, new_comb}});
}
}
}
}
return res;
}
};