Subsets - LeetCode

Given a set of distinct integers, nums, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • 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],
  []
]

思路:将nums数组先排序。然后依次枚举每一位在或者不在的情况。根据要求,当我们枚举了某一位为存在的情况时,则该位前面的数都不能再枚举了,因为要求结果是增长序列。此外,记得不要漏了空集的情况。

 1 class Solution {
 2 public:
 3     void help(vector<vector<int> >& res, vector<int>& nums, vector<int>& cur, int st)
 4     {
 5         if (st == nums.size())
 6             return;
 7         for (int i = st, n = nums.size(); i < n; i++)
 8         {
 9             cur.push_back(nums[i]);
10             res.push_back(cur);
11             help(res, nums, cur, i + 1);
12             cur.erase(cur.begin() + cur.size() - 1);
13         }
14     }
15     vector<vector<int>> subsets(vector<int>& nums) {
16         sort(nums.begin(), nums.end(), less<int>());
17         vector<vector<int> > res;
18         vector<int> tem;
19         res.push_back(tem);
20         help(res, nums, tem, 0);
21         return res;
22     }
23 };

 

posted @ 2015-11-10 14:16  fenshen371  阅读(171)  评论(0编辑  收藏  举报