题目
链接:https://leetcode.com/problems/subsets/
Level: Medium
Discription:
Given a set of distinct integers, nums, return all possible subsets (the power set).
Example 1:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Note:
- The solution set must not contain duplicate subsets.
代码
class Solution {
public:
void dfs(vector<int>& nums, vector<int>& temp, vector<vector<int>>& ret,int n, int index)
{
if(n == temp.size())
{
ret.push_back(temp);
return;
}
for(int i=index;i<nums.size();i++)
{
if((n-temp.size()) > (nums.size()-i))
return;
temp.push_back(nums[i]);
dfs(nums, temp, ret, n, i+1);
temp.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> temp;
vector<vector<int>> ret;
for(int i=0;i<=nums.size();i++)
{
dfs(nums, temp, ret, i, 0);
}
return ret;
}
};
思考
- 算法时间复杂度为O(\(2^n\)),指数级的复杂度一般在求全部解的问题中会出现,空间复杂度为O(n)。
- 求n个元素的所有子集。