78. Subsets
问题描述:
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
解题思路:
可以用dfs来解。
我们每对可能子集数组v进行一次操作,就要将其加入返回数组!
不要忘记空集是任何集合的子集!
代码:
class Solution { public: vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> ret; vector<int> v; ret.push_back(v); if(nums.empty()) return ret; dfs(ret, 0, v, nums); return ret; } private: void dfs(vector<vector<int>> &ret, int start, vector<int> &v, vector<int> &nums){ if(start >= nums.size()) return; for(int i = start; i < nums.size(); i++){ v.push_back(nums[i]); ret.push_back(v); dfs(ret, i+1, v, nums); v.pop_back(); } } };