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],
[]
]
和上题类似,都是简单dfs,枚举起点,列举不同起点的所有情况。
class Solution {
void dfs(int b, vector<int> &nums, vector<int> &res, vector<vector<int>> &ans) {
ans.push_back(res);
if(b == nums.size())
return ;
for(int i=b; i < nums.size(); ++ i)
{
res.push_back(nums[i]);
dfs(i+1, nums, res, ans);
res.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> res;
dfs(0, nums, res, ans);
return ans;
}
};