LeetCode 90:Subsets II

Datetime:2016-08-23 01:21:37          Topic: LeetCode           Share

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




About List