Leetcode90. 子集 II
相似题目:Leetcode78. 子集
题目:
给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
题解:
方案一:迭代
方案二:二进制掩码
java代码:
/**
* 迭代
*
* @param nums
* @return
*/
public static List<List<Integer>> subsetsWithDup3(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> output = new ArrayList<>();
output.add(new ArrayList<>());
int start = 1;
for (int i = 0; i < nums.length; i++) {
List<List<Integer>> ans_tmp = new ArrayList<>();
// 遍历之前的所有结果
for (int j = 0; j < output.size(); j++) {
List<Integer> list = output.get(j);
//如果出现重复数字,就跳过所有旧解
if (i > 0 && nums[i] == nums[i - 1] && j < start) {
continue;
}
List<Integer> tmp = new ArrayList<>(list);
tmp.add(nums[i]); // 加入新增数字
ans_tmp.add(tmp);
}
start = output.size(); //更新新解的开始位置
output.addAll(ans_tmp);
}
return output;
}
/**
* 二进制方式
*
* @param nums
* @return
*/
public static List<List<Integer>> subsetsWithDup4(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> output = new ArrayList<>();
int n = nums.length;
for (int i = (int) Math.pow(2, n); i < (int) Math.pow(2, n + 1); i++) {
String substring = Integer.toBinaryString(i).substring(1);
boolean flag = true;
List<Integer> list = new ArrayList<>();
for (int j = 0; j < n; j++) {
if (substring.charAt(j) == '1') {
//当前是重复数字,并且前一位是 0,跳过这种情况
if (j > 0 && nums[j] == nums[j - 1] && substring.charAt(j - 1) == '0') {
flag = false;
break;
} else {
list.add(nums[j]);
}
}
}
if (flag) {
output.add(list);
}
}
return output;
}
本文详细解析了LeetCode 90 子集II的题目要求,提供了两种解决方案:迭代法和二进制掩码法。通过示例展示了如何去除重复子集,适用于算法学习和面试准备。
765

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



