Subsets II -- LeetCode
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Subsets II -- LeetCode相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章