-
Notifications
You must be signed in to change notification settings - Fork 4
/
Subsets.txt
80 lines (74 loc) · 1.83 KB
/
Subsets.txt
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
problem:
Given a set of distinct integers, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
----------------------------------------------------------------
solution:
排列组合中的排列问题。
//思路一、二进制法。题目要求结果组合中数字按升序排列,因此刚开始需对数组排序。
vector<vector<int> > subsets(vector<int> &S)
{
vector<vector<int> > ret;
int n = S.size();
if(n == 0)
return ret;
sort(S.begin(), S.end());
int maxNum = 1 << n;
for(int i = 0; i < maxNum; ++i)
{
vector<int> subset;
int idx = 0;
int j = i;
while(j > 0)
{
if(j & 1)
subset.push_back(S[idx]);
j = j >> 1;
++idx;
}
ret.push_back(subset);
}
return ret;
}
//思路二、标志位法。题目要求结果组合中数字按升序排列,因此刚开始需对数组排序。
void subsets_aux(int idx, vector<int> &S, vector<vector<int> > &ret, vector<bool> &isVisited)
{
if(idx == S.size())
{
vector<int> tmp;
for(int i = 0; i < S.size(); ++i)
{
if(isVisited[i])
tmp.push_back(S[i]);
}
ret.push_back(tmp);
return;
}
isVisited[idx] = true;
subsets_aux(idx + 1, S, ret, isVisited);
isVisited[idx] = false;
subsets_aux(idx + 1, S, ret, isVisited);
}
vector<vector<int> > subsets(vector<int> &S)
{
vector<vector<int> > ret;
if(S.size() == 0)
return ret;
sort(S.begin(), S.end());
vector<bool> isVisited(S.size(), false);
subsets_aux(0, S, ret, isVisited);
return ret;
}