forked from illuz/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAC_dfs_n!.cpp
More file actions
63 lines (58 loc) · 1.6 KB
/
Copy pathAC_dfs_n!.cpp
File metadata and controls
63 lines (58 loc) · 1.6 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
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_dfs_n!.cpp
* Create Date: 2015-01-01 11:35:04
* Descripton: just as the version I
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
class Solution {
private:
void dfs(vector<vector<int> > &ans, vector<int> &single,
vector<int> &candi, int cur, int rest) {
int sz = candi.size();
if (rest == 0) {
// to avoid [[1,1,1], 2]
if (!single.empty() && cur < sz && single[single.size() - 1] == candi[cur])
return;
ans.push_back(single);
return;
}
if (sz <= cur || rest < 0)
return;
// choose cur
single.push_back(candi[cur]);
dfs(ans, single, candi, cur + 1, rest - candi[cur]);
single.pop_back();
// don't choose cur
// not contain duplicate combinations
if (!single.empty() && single[single.size() - 1] == candi[cur])
return;
dfs(ans, single, candi, cur + 1, rest);
}
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
vector<vector<int> > ans;
vector<int> single;
sort(num.begin(), num.end());
dfs(ans, single, num, 0, target);
return ans;
}
};
int main() {
int tar;
int n;
Solution s;
cin >> n >> tar;
vector<int> v(n);
for (int i = 0; i < n; i++)
cin >> v[i];
vector<vector<int> > res = s.combinationSum2(v, tar);
for (auto &i : res) {
for (auto &j : i)
cout << j << ' ';
puts("");
}
return 0;
}