-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39.combination-sum.cpp
More file actions
58 lines (46 loc) · 1.36 KB
/
39.combination-sum.cpp
File metadata and controls
58 lines (46 loc) · 1.36 KB
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
/*
* @lc app=leetcode id=39 lang=cpp
*
* [39] Combination Sum
*/
// @lc code=start
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <stack>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> result;
// selected list, index, sum
stack<pair<vector<int>, pair<int, int>>> stk;
sort(candidates.begin(), candidates.end(), [](int x1, int x2) -> bool { return x1 < x2; });
for (int i = 0; i < candidates.size(); i++) {
stk.push({ vector { candidates[i] }, { i, candidates[i] } });
}
while(!stk.empty()) {
auto list = stk.top().first;
int index = stk.top().second.first;
int sum = stk.top().second.second;
stk.pop();
if(sum == target) {
result.push_back(list);
continue;
}
else if (sum > target) {
continue;
}
for (int i = index; i < candidates.size(); i++) {
vector<int> copy = list;
copy.push_back(candidates[i]);
stk.push({ copy, { i, sum + candidates[i]} });
}
}
return result;
}
};
// @lc code=end