Tags: leetcode
1. 题目描述
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
2. 题解
解法一:
利用位操作,对于一个长度为n的数组nums,考虑到其子集的个数为2^n,所以可产生0到2^n – 1的数,每一个数对应一个子集,并对每一个这样的数i检查nums的每一个下标j对应的二进制位是否为1,为1则nums[j]是该子集的一个元素。将每个i对应的子集作为结果的一个元素,即可。
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
//6ms
vector<vector<int>> ret;
if (nums.empty()) {
ret.push_back(vector<int>());
return ret;
}
const int N = (1 << nums.size());
for (int i = 0; i < N; ++i) {
vector<int> v;
for (int j = 0; j < nums.size(); ++j) {
if (i & (1 << j))
v.push_back(nums[j]);
}
ret.push_back(v);
}
return ret;
}
};
解法二
对于每一个元素可放入或不放入一个给定集合中,算法类似于求全排列
class Solution {
public:
void getSubs(vector<int>& nums, int start, vector<int>& sub, vector<vector<int> >& subs) {
subs.push_back(sub);
for (int i = start; i < nums.size(); ++i) {
sub.push_back(nums[i]);
getSubs(nums, i + 1, sub, subs);
sub.pop_back();
}
}
vector<vector<int> > subsets(vector<int>& nums) {
vector<vector<int> > subs;
vector<int> sub;
getSubs(nums, 0, sub, subs);
return subs;
}
};