当前位置: 首页 > article >正文

【Leetcode 每日一题】90. 子集 II

问题背景

给你一个整数数组 n u m s nums nums,其中可能包含重复元素,请你返回该数组所有可能的 子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。

数据约束

1 ≤ n u m s . l e n g t h ≤ 10 1 \le nums.length \le 10 1nums.length10
− 10 ≤ n u m s [ i ] ≤ 10 -10 \le nums[i] \le 10 10nums[i]10

解题过程

经典回溯问题,在 没有重复元素的版本 实现的基础上,跳过重复元素就可以了。

具体实现

选或不选

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        dfs(0, nums, res, path);
        return res;
    }

    private void dfs(int i, int[] nums, List<List<Integer>> res, List<Integer> path) {
        int n = nums.length;
        if (i == n) {
            res.add(new ArrayList<>(path));
            return;
        }
        int cur = nums[i];
        path.add(cur);
        dfs(i + 1, nums, res, path);
        path.remove(path.size() - 1);
        i++;
        while (i < n && nums[i] == cur) {
            i++;
        }
        dfs(i, nums, res, path);
    }
}

选哪一个

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        dfs(0, nums, res, path);
        return res;
    }

    private void dfs(int i, int[] nums, List<List<Integer>> res, List<Integer> path) {
        res.add(new ArrayList<>(path));

        for (int j = i; j < nums.length; j++) {
            if (j > i && nums[j] == nums[j - 1]) {
                continue;
            }
            path.add(nums[j]);
            dfs(j + 1, nums, res, path);
            path.remove(path.size() - 1);
        }
    }
}

http://www.kler.cn/a/535344.html

相关文章:

  • 记录一下 在Mac下用pyinstallter 打包 Django项目
  • 【码道初阶】Leetcode540. 有序数组中的单一元素,异或运算在二分查找的优雅实现(附异或运算详解)
  • 网络爬虫js逆向之某音乐平台案例
  • pytorch实现门控循环单元 (GRU)
  • HTML5 教程之标签(3)
  • CNN的各种知识点(四): 非极大值抑制(Non-Maximum Suppression, NMS)
  • 基于多重算法的医院增强型50G全光网络设计与实践:构建智慧医疗新基石(上)
  • MS SQL Server partition by 函数实战二 编排考场人员
  • vite共享配置之---css相关
  • 【玩转 Postman 接口测试与开发2_018】第14章:利用 Postman 初探 API 安全测试
  • MAC OS安装Homebrew
  • android用eclipse开发碰到65535问题的完美解决方案
  • DMZ区的作用和原则
  • 【Windows 开发NVIDIA相关组件】CUDA、cuDNN、TensorRT
  • 3.5 Go(特殊函数)
  • 计算机毕业设计hadoop+spark+hive民宿推荐系统 酒店推荐系统 民宿价格预测 酒店价预测 机器学习 深度学习 Python爬虫 HDFS集群
  • 嵌入式硬件篇---OpenMV基本使用自动增益\曝光\白平衡
  • Unity VideoPlayer播放视屏不清晰的一种情况
  • 网络安全风险量化值 网络安全风险控制
  • C# OpenCV机器视觉:利用TrashNet实现垃圾分类
  • Google地图瓦片爬虫——进阶版
  • 计算机网络之物理层通信基础(电路交换、报文交换与分组交换)
  • go函数详解
  • ONLYOFFICE 文档 8.3 已发布:PDF 图章、合并形状、更多格式支持等
  • 【电商数据分析项目经验分享】数据采集——数据清洗——数据分析与可视化——数据决策”
  • Pixflow - CL-DJI Drone LUTs 120个大疆Drone无人机相机航拍电影级镜头LUT调色预设