【LeetCode OJ 090】Subsets II

题目链接:https://leetcode.com/problems/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],
  []
]
解题思路:这题与第78题相似,不同之处在于这题给定的数组中重复的数字,参照78题思路,再利用HashSet就可以过滤掉重复的list,具体实现见下面代码:

public class Solution
{
	public List<List<Integer>> subsetsWithDup(int[] nums) 
	{
		List<List<Integer>> result=new ArrayList<List<Integer>>();
		HashSet<List<Integer>> temp=new HashSet<List<Integer>>();
		//先对数组进行排序
		Arrays.sort(nums);
		int n=nums.length;
		//1<<n就是该数组子集的个数
		for(int i=0;i<(1<<n);i++)
		{
			List<Integer> list=new ArrayList<Integer>();
			for(int j=0;j<n;j++)
			{
				//(i&(1<<j))!=0表示数组中索引值为j的数在当前的子集中
				if((i&(1<<j))!=0)
				{
					list.add(nums[j]);
				}
			}
			//先将结果放入HashSet中,这样就可以过滤掉重复的list
			temp.add(list);
		}
		for(List<Integer> list:temp)
		{
			result.add(list);
		}
		return result;
    }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值