forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinationSum2.cpp
More file actions
69 lines (63 loc) · 1.89 KB
/
combinationSum2.cpp
File metadata and controls
69 lines (63 loc) · 1.89 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
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define RFOR(i,a,b) for(int i=(a);i>=(b);--i)
typedef long long LL;
vector<int> cc;
int n;
vector<vector<bool> > flag;
vector<vector<vector<vector<int> > > > mm;
class Solution {
public:
vector<vector<int> > doit(int idx, int t) {
if (flag[idx][t]) return mm[idx][t];
if (idx == n) {
flag[idx][t] = true;
return mm[idx][t];
}
int ti = idx + 1;
while (ti < n && cc[ti] == cc[idx]) ++ti;
mm[idx][t] = doit(ti, t);
int now = cc[idx];
if (now < t) {
vector<vector<int> > tmp = doit(idx + 1, t - now);
REP(i,tmp.size()) {
vector<int> tt;
tt.push_back(cc[idx]);
REP(j,tmp[i].size()) tt.push_back(tmp[i][j]);
mm[idx][t].push_back(tt);
}
}
if (now == t) {
vector<int> tt;
tt.push_back(cc[idx]);
mm[idx][t].push_back(tt);
}
flag[idx][t] = true;
return mm[idx][t];
}
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
cc = num;
sort(cc.begin(), cc.end());
n = cc.size();
flag.assign(n + 5, vector<bool>(target + 5, false));
mm.assign(n + 5, vector<vector<vector<int> > >(target + 5));
vector<vector<int> > res = doit(0, target);
return res;
}
};
int main() {
int data[] = {10,1,2,7,6,1,5};
vector<int> can;
REP(i,7) can.push_back(data[i]);
Solution s;
vector<vector<int> > res = s.combinationSum2(can, 8);
REP(i,res.size()) {
REP(j,res[i].size()) cout << res[i][j] << " ";
cout << endl;
}
return 0;
}