-
Notifications
You must be signed in to change notification settings - Fork 0
/
77. 组合.cc
86 lines (79 loc) · 1.9 KB
/
77. 组合.cc
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
79
80
81
82
83
84
85
86
class Solution {
public:
vector<vector<int>> combine(int n, int k)
{
vector<vector<int>> res;
res.reserve();
backtrace(res, vector<int>(), 1, n, k);
return res;
}
void backtrace(vector<vector<int>> &res, vector<int> subres, int start, int n, int k)
{
if(subres.size() == k)
{
res.push_back(subres);
return ;
}
for(int i=start; i<=n; ++i)
{
if(find(subres.begin(), subres.end(), i) != subres.end()) continue;
subres.push_back(i);
backtrace(res, subres, i+1, n, k);
subres.pop_back();
}
}
};
/* 优化 */
class Solution {
int n, k;
vector<vector<int>> res;
public:
vector<vector<int>> combine(int n, int k)
{
this->n = n; this->k = k;
backtrace(vector<int>(), 1);
return res;
}
void backtrace(vector<int> subres, int start)
{
if(subres.size() == k)
{
res.push_back(subres);
return ;
}
for(int i=start; i<=n; ++i)
{
subres.push_back(i);
backtrace(subres, i+1);
subres.pop_back();
}
}
};
/* 剪枝 */
class Solution {
int n, k;
vector<vector<int>> res;
public:
vector<vector<int>> combine(int n, int k)
{
if(n<1 || k<1 || k>n) return res;
this->n = n; this->k = k;
backtrace(vector<int>(), 1);
return res;
}
void backtrace(vector<int> subres, int start)
{
if(subres.size() == k)
{
res.push_back(subres);
return ;
}
/* 保证start到n-(k-subres.size())+1有足够的元素容下k大小的解 */
for(int i=start; i<=n-(k-subres.size())+1; ++i)
{
subres.push_back(i);
backtrace(subres, i+1);
subres.pop_back();
}
}
};