-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathp040.cpp
79 lines (76 loc) · 2.16 KB
/
p040.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class Solution {
public:
set<int> *mem;
bool f(const int *a, const int pos, const int target, const int len, vector<vector<int>> &result, vector<int> &s)
{
if (target == 0)
{
result.push_back(s);
return true;
}
if (mem[pos].find(target) != mem[pos].end()) return false;
bool ret = false;
if (pos < len-1)
{
if (target >= a[pos+1])
{
s.push_back(a[pos+1]);
ret |= f(a, pos+1, target-a[pos+1], len, result, s);
s.pop_back();
}
}
for (int i = pos+2; i < len; i++)
{
if (a[i] != a[i-1])
{
if (target >= a[i])
{
s.push_back(a[i]);
ret |= f(a, i, target-a[i], len, result, s);
s.pop_back();
}
else
{
break;
}
}
}
if (!ret) mem[pos].insert(target);
return ret;
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
int len = candidates.size();
int *a;
vector<vector<int>> result;
vector<int> s;
if (len == 0) return result;
a = new int[len];
mem = new set<int>[len];
for (int i = 0; i < len; i++)
{
a[i] = candidates[i];
}
sort(a, a+len);
if (target >= a[0])
{
s.push_back(a[0]);
f(a, 0, target-a[0], len, result, s);
s.pop_back();
for (int i = 1; i < len; i++)
if (a[i] != a[i-1])
{
if (target >= a[i])
{
s.push_back(a[i]);
f(a, i, target-a[i], len, result, s);
s.pop_back();
}
else
{
break;
}
}
}
return result;
}
};