Given a set of distinct integers, return all possible subsets.
Notice
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
Example
If S = [1,2,3]
, a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Challenge
Can you do it in both recursively and iteratively?
题意
给定一个含不同整数的集合,返回其所有的子集
注意事项
子集中的元素排列必须是非降序的,解集必须不包含重复的子集
解法一:
1 class Solution { 2 public: 3 /* 4 * @param nums: A set of numbers 5 * @return: A list of lists 6 */ 7 vector<vector<int>> subsets(vector<int> &nums) { 8 // write your code here 9 vector<vector<int> > results; 10 vector<int> result; 11 12 sort(nums.begin(), nums.end()); 13 14 helper(nums, 0, result, results); 15 16 return results; 17 } 18 19 void helper(vector<int> &nums, int start, vector<int> & result, vector<vector<int> > & results) 20 { 21 results.push_back(result); 22 23 for (int i = start; i < nums.size(); ++i) { 24 result.push_back(nums[i]); 25 26 helper(nums, i + 1, result, results); 27 28 result.pop_back(); 29 } 30 } 31 };