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

Subsets II -- LeetCode

时间:2016-01-24 06:59:33      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

Given a collection of integers that might contain duplicates, 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,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

思路:我们先考虑所有数字不重复出现的情况。那么所有子集的个数是2^n,即每个数字都只有出现或者不出现这2种情况。而当数字重复出现时,我们将该数字视为一种特殊的数字。比如说输入中含有2个5,那么我们就有3种选择:不选5,选1个5,选2个5。
 1 class Solution {
 2 public:
 3     void help(vector<vector<int> >& res, vector<int>& nums, vector<int> cand, int cur)
 4     {
 5         if (cur == nums.size())
 6         {
 7             res.push_back(cand);
 8             return;
 9         }
10         int nex, n = nums.size();
11         for (nex = cur + 1; nex < n && nums[nex] == nums[cur]; nex++);
12         help(res, nums, cand, nex);
13         for (int i = cur; i < nex; i++)
14         {
15             cand.push_back(nums[i]);
16             help(res, nums, cand, nex);
17         }
18     }
19     vector<vector<int>> subsetsWithDup(vector<int>& nums) {
20         sort(nums.begin(), nums.end(), less<int>());
21         vector<int> cand;
22         vector<vector<int> > res;
23         help(res, nums, cand, 0);
24         return res;
25     }
26 };

 

 

Subsets II -- LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/5154486.html

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