Subsets
Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
DFS+位运算
枚举每一个元素出现/不出现在subset中。因为用32位的unsigned int,所以最多能记录32个元素的集合,超过32个的话数目太多,题目肯定不会检验。
class Solution {
public:
vector<vector<int> > subsets(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int> > res;
flag = 0;
helper(nums, res, 0);
return res;
}
private:
void helper(vector<int>& nums, vector<vector<int> >& res, int k){
int n = nums.size();
if(k == n){
vector<int> tmp;
for(unsigned int i = 0, b = 1; i < n; i++){
if(b&flag) tmp.push_back(nums[i]);
b <<= 1;
}
res.push_back(tmp);
return;
}
helper(nums, res, k+1);
flag |= (1<<k);
helper(nums, res, k+1);
flag ^= (1<<k);
}
unsigned int flag;
};