Description:
- Difficulty:Medium
- Total Accepted:204.6K
- Total Submissions:475.3K
- Contributor:LeetCode
Given a set of distinct integers, nums, return all possible subsets (the power set).
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], [] ]
Thought:
在原有的集合中对每集合中的每个元素都加入新元素得到子集,然后放入原有集合中。
如果没有元素就返回空集(没有元素的数组)。
Code:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
return helper(nums, nums.size() - 1);
}
vector<vector<int>> helper(vector<int>& nums, int index)
{
if (index == -1)
{
vector<vector<int>> res = vector<vector<int>>();
vector<int> elem = vector<int>();
res.push_back(elem);
return res;
}
vector<vector<int>> res = helper(nums, index - 1);
int size = res.size();
for (int i = 0; i<size; i++)
{
vector<int> elem = vector<int>(res[i]);
elem.push_back(nums[index]);
res.push_back(elem);
}
return res;
}
};