Leetcode90. 子集 II

本文详细解析了LeetCode 90 子集II的题目要求,提供了两种解决方案:迭代法和二进制掩码法。通过示例展示了如何去除重复子集,适用于算法学习和面试准备。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值