题目描述:
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], [] ]解题思路:
使用位操作,n个元素的数组有2^n个子集,包括从空集到全集,可以使用0到2^n-1的二进制位来表示,
0的二进制均为0对应于空集,2^n-1的二进制位有n个1对应于全集
AC代码如下:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> ans;
int n = nums.size();
if (n <= 0) return ans;
for (int i = 0; i < (1 << n); ++i){
vector<int> tmp;
for (int j = 0; j < n; ++j){
if (i&(1 << j)){
tmp.push_back(nums[j]);
}
}
ans.push_back(tmp);
}
return ans;
}
};