-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathp039.cpp
53 lines (50 loc) · 1.24 KB
/
p039.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
class Solution {
public:
vector<vector<int>> result;
int len;
int *num;
int *multi;
void f(int target, int pos) {
if (target == 0)
{
int newlen = 0;
for (int i = 0; i < pos; i++)
{
newlen += multi[i];
}
vector<int> newv(newlen);
newlen = 0;
for (int i = 0; i < pos; i++)
for (int j = 0; j < multi[i]; j++)
newv[newlen++] = num[i];
result.push_back(newv);
return;
}
if (pos >= len)
{
return;
}
f(target, pos+1);
int val = num[pos];
target -= val;
while (target >= 0)
{
multi[pos]++;
f(target, pos+1);
target -= val;
}
multi[pos] = 0;
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
len = candidates.size();
num = new int[len];
multi = new int[len];
for (int i = 0; i < len; i++)
{
num[i] = candidates[i];
multi[i] = 0;
}
f(target, 0);
return result;
}
};