题目链接: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;
}
}

本文详细介绍了如何解决LeetCode中的子集II问题,包括使用排序数组和HashSet来过滤重复子集的方法。

被折叠的 条评论
为什么被折叠?



