给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<Integer> list = new ArrayList<>();
Set<List<Integer>> ans = new HashSet<>();
int n = nums.length;
for(int i = 0;i < (1 << n);i++){
list.clear();
for(int j = 0;j < n;j++){
if((i & (1 << j)) > 0){
list.add(nums[j]);
}
}
ans.add(new ArrayList<>(list));
}
return new ArrayList<>(ans);
}
}
该博客介绍了如何使用Java编程解决找到一个整数数组的所有不重复子集问题。通过排序输入数组,利用位运算,遍历所有可能的二进制组合来生成子集,并用HashSet去除重复。这种方法适用于处理包含重复元素的数组,且能够有效地生成所有子集。

391

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



