【Leetcode 热题 100】78. 子集

问题背景

给你一个整数数组 n u m s nums nums,数组中的元素 互不相同 。返回该数组所有可能的 子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

数据约束

  • 1 ≤ n u m s . l e n g t h ≤ 10 1 \le nums.length \le 10 1≤nums.length≤10
  • − 10 ≤ n u m s [ i ] ≤ 10 -10 \le nums[i] \le 10 −10≤nums[i]≤10
  • n u m s nums nums中的所有元素 互不相同

解题过程

子集问题同样可以考虑每个位置上选或不选,或者每一次选哪个元素。

具体实现

选或不选

java 复制代码
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        dfs(0, nums, path, res);
        return res;
    }

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

选哪一个

java 复制代码
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        dfs(0, nums, path, res);
        return res;
    }

    private void dfs(int i, int[] nums, List<Integer> path, List<List<Integer>> res) {
        res.add(new ArrayList<>(path));
        // 注意 j 要从 i 开始枚举,不要走回头路
        for(int j = i; j < nums.length; j++) {
            path.add(nums[j]);
            dfs(j + 1, nums, path, res);
            path.remove(path.size() - 1);
        }
    }
}
相关推荐
历程里程碑1 小时前
Linux22 文件系统
linux·运维·c语言·开发语言·数据结构·c++·算法
YGGP2 小时前
【Golang】LeetCode 128. 最长连续序列
leetcode
你撅嘴真丑8 小时前
第九章-数字三角形
算法
uesowys8 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder8 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮9 小时前
AI 视觉连载1:像素
算法
智驱力人工智能9 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
孞㐑¥10 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
月挽清风10 小时前
代码随想录第十五天
数据结构·算法·leetcode
XX風10 小时前
8.1 PFH&&FPFH
图像处理·算法