码迷,mamicode.com
首页 > 其他好文 > 详细

17. Subsets【medium】

时间:2018-01-20 12:40:50      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:challenge   element   pre   set   col   [1]   sub   numbers   注意   

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 };

 

17. Subsets【medium】

标签:challenge   element   pre   set   col   [1]   sub   numbers   注意   

原文地址:https://www.cnblogs.com/abc-begin/p/8320173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!