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;
	}
};


posted on 2018-02-08 12:40  yjbjingcha  阅读(112)  评论(0编辑  收藏  举报

导航