给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
\\ 方法一:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
int n = pow(2, nums.size());
for(int i = 0 ; i < n; i ++)
{
vector<int> temp;
int m = i;
for(int j = 0; j < nums.size(); j++)
{
if( m & 1 )
temp.push_back(nums[j]);
m >>= 1;
}
res.push_back(temp);
}
return res;
}
};
==================================================================
\\ 方法二:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> temp;
fun(nums, 0, res, temp);
return res;
}
void fun(auto& nums, int count, auto& res, auto& temp)
{
if(count <= nums.size())
res.push_back(temp);
for(int i = count; i < nums.size(); i++)
{
temp.push_back(nums[i]);
fun(nums, i + 1, res, temp);
temp.pop_back();
}
}
};