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(n为集合元素个数),所以这里可以用bitmap记录每个元素是否选中
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
int len = nums.size();
vector<vector<int> > res;
int cnt = pow(2, len);
for (int i = 0; i < cnt; ++i)
{
vector<int> tmp;
int j = i;
int t = 0;
while(j) {
if (j & 1) tmp.push_back(nums[t]);
t++;
j >>= 1;
}
res.push_back(tmp);
}
return res;
}
};