forked from sunstick/code-street
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination_sum_II.cpp
More file actions
78 lines (64 loc) · 2.19 KB
/
combination_sum_II.cpp
File metadata and controls
78 lines (64 loc) · 2.19 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
*/
class Solution {
public:
void search_path(vector<vector<int> > &path, int **dp, vector<int> &v, int i, int j, vector<int> &num) {
if (j == 0) {
if (find(path.begin(), path.end(), v) == path.end())
path.push_back(v);
return ;
}
if (i <= 0) return ;
if (dp[i][j] == 3 || dp[i][j] == 2) {
search_path(path, dp, v, i - 1, j, num);
}
if (dp[i][j] == 3 || dp[i][j] == 1) {
v.push_back(num[i - 1]);
search_path(path, dp, v, i - 1, j - num[i - 1], num);
v.pop_back();
}
}
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
sort(num.begin(), num.end());
reverse(num.begin(), num.end());
int n = num.size();
int **dp = new int*[n + 1];
for (int i = 0; i <= n; i++) {
dp[i] = new int [target + 1];
memset(dp[i], 0, sizeof(dp[i]));
}
dp[0][0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= target; j++) {
dp[i][j] = 0;
if (j >= num[i - 1]) {
if (dp[i - 1][j - num[i - 1]])
dp[i][j] += 1;
if (dp[i - 1][j])
dp[i][j] += 2;
} else {
if (dp[i - 1][j])
dp[i][j] += 2;
}
}
}
vector<vector<int> > path;
vector<int> v;
for (int i = 1; i <= n; ++i)
if (dp[i][target])
search_path(path, dp, v, i, target, num);
return path;
}
};