LeetCode 90:Subsets II

Posted zhihua_bupt

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 90:Subsets II相关的知识,希望对你有一定的参考价值。

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],
  []
]

Subscribe to see which companies asked this question

这题有重复元素,但本质上,跟上题很类似,也可以用类似的方法处理:

class Solution {
public:
	vector<vector<int>> subsetsWithDup(vector<int>& nums) {
		vector<vector<int>> ans(1, vector<int>());
		sort(nums.begin(), nums.end());
		
		int pre_size = 0;
		for (int i = 0; i < nums.size(); i++)
		{
			int n = ans.size();
			for (int j = 0; j < n; j++) //第二个for循环是为了求得包含nums[i]的所有子集  
			{
				if (i == 0 || nums[i] != nums[i -1] || j>=pre_size)
				{
					ans.push_back(ans[j]); //在尾部重新插入ans已经存在的子集  
					ans.back().push_back(nums[i]); //将nums[i]添加进去 
				}
			}
			pre_size = n;
		}
		return ans;
	}
};

技术分享

以上是关于LeetCode 90:Subsets II的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 90. Subsets II 子集合 II

Leetcode 90. Subsets II

[leetcode-90-Subsets II]

Leetcode 90: Subsets II

Leetcode 90. Subsets II

LeetCode 90. Subsets II