forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
40.cpp
70 lines (59 loc) · 1.84 KB
/
40.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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int> > ans;
vector<bool> flag(candidates.size(), false);
vector<int> temp;
combinationSum2Helper(ans, flag, temp, candidates, target);
return ans;
}
/* Very slow, 424 ms. Need to improved. */
void combinationSum2Helper(vector<vector<int> > &ans, vector<bool> &flag, vector<int> &temp, vector<int> &candidates, int target) {
if (target == 0) {
bool found = false;
for (vector<vector<int> >::iterator it = ans.begin(); it != ans.end(); it++) {
if (temp == *it) {
found = true;
break;
}
}
if (!found)
ans.push_back(temp);
return;
}
else if (target < 0) {
return;
}
int max = 0;
for (int k = 0; k < temp.size(); k++) {
if (temp[k] > max)
max = temp[k];
}
for (int i = 0; i < candidates.size(); i++) {
if (!flag[i] && candidates[i] >= max) {
flag[i] = true;
temp.push_back(candidates[i]);
combinationSum2Helper(ans, flag, temp, candidates, target - candidates[i]);
temp.pop_back();
flag[i] = false;
}
}
}
};
int main() {
vector<int> candidates = {10, 1, 2, 7, 6, 1, 5};
int target = 8;
Solution s;
vector<vector<int> > ans = s.combinationSum2(candidates, target);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++) {
printf("%d ", ans[i][j]);
}
printf("\n");
}
return 0;
}