forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombination-sum(AC).cpp
64 lines (61 loc) · 1.4 KB
/
combination-sum(AC).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
#include <algorithm>
#include <unordered_set>
using namespace std;
class Solution {
public:
/**
* @param candidates: A list of integers
* @param target:An integer
* @return: A list of lists of integers
*/
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
v.clear();
us.clear();
a.clear();
ans.clear();
n = candidates.size();
int i;
for (i = 0; i < n; ++i) {
us.insert(candidates[i]);
}
for (auto it = us.begin(); it != us.end(); ++it) {
a.push_back(*it);
}
n = a.size();
sort(a.begin(), a.end());
t = target;
DFS(0, 0);
return ans;
}
private:
vector<int> v;
unordered_set<int> us;
vector<int> a;
vector<vector<int> > ans;
int n;
int t;
void DFS(int idx, int sum) {
if (sum == t) {
ans.push_back(v);
return;
}
if (idx == n) {
return;
}
if (sum + a[idx] > t) {
return;
}
int i = 0;
int j;
while (sum + i * a[idx] <= t) {
for (j = 0; j < i; ++j) {
v.push_back(a[idx]);
}
DFS(idx + 1, sum + i * a[idx]);
for (j = 0; j < i; ++j) {
v.pop_back();
}
++i;
}
}
};