标签:
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
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 };
标签:
原文地址:http://www.cnblogs.com/fenshen371/p/5154486.html