LeetCode subsets

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。 示例:

输入: nums = [1,2,3] 输出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []]

解答:

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
class Solution {
public:
vector<vector<int>> subsets1(vector<int>& nums) {
if (nums.empty()) return {};
int len = nums.size();
vector<vector<int>> res;
res.push_back({});
for (int i = len - 1; i >= 0; --i) {
int tmpLen = res.size();
for (int j = 0; j < tmpLen; ++j) {
vector<int> tmp = res[j];
tmp.push_back(nums[i]);
res.push_back(tmp);
}
}
return res;
}

vector<vector<int>> subsets2(vector<int>& nums) {
vector<vector<int>> ret;
ret.push_back({});
int size = nums.size();
int subsize = pow(2,size);
int hash = 1;
while (hash < subsize) {
vector<int> temp;
for (int k = 0; k < size; ++k) {
int a = 1 << k;
if(a & hash)
temp.push_back(nums[k]);
}
ret.push_back(temp);
++hash;
}
return ret;
}

vector<vector<int>> subsets3(vector<int>& nums) {
vector<vector<int> > res;
vector<int> tmp;
helper(res, tmp, nums, 0);
return res;
}
void helper(vector<vector<int>> &res, vector<int> tmp, vector<int> &nums, int level) {
if (tmp.size() <= nums.size())
res.push_back(tmp);

for(int i = level; i < nums.size(); i++){
tmp.push_back(nums[i]);
helper(res, tmp, nums, i+1);
tmp.pop_back();
}
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×