-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path40.combination-sum-ii.cpp
65 lines (51 loc) · 1.62 KB
/
40.combination-sum-ii.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* @lc app=leetcode id=40 lang=cpp
*
* [40] Combination Sum II
*/
// @lc code=start
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
class Solution {
public:
// incomplete answer..
vector<vector<int>> combinationSum2(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) {
if(find(result.begin(), result.end(), list) == result.end())
result.push_back(list);
continue;
}
else if (sum > target) {
continue;
}
for (int i = index - 1; i >= 0; i--) {
vector<int> copy = list;
copy.push_back(candidates[i]);
stk.push({ copy, { i, sum + candidates[i]} });
// incomplete check duplicate. (but boost speed)
while(i > 0 && candidates[i] == candidates[i - 1]) i--;
}
}
return result;
}
};
// @lc code=end