【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);
        }
    }
}
相关推荐
生成论实验室几秒前
用事件关系网络重新理解AI(二):损失函数、优化器与深度学习的动力学
数据结构·人工智能·深度学习·算法·语言模型
霍霍的袁7 分钟前
【C++初阶】缺省参数(默认参数)详细讲解
开发语言·c++·算法
计算机安禾13 分钟前
【算法分析与设计】第2篇:计算模型与渐进复杂性分析
算法
生成论实验室18 分钟前
事件、信息荷与六维态势空间——每一个事件都是一次空间的弯曲
人工智能·算法·语言模型·可信计算技术·安全架构
budingxiaomoli23 分钟前
递归,搜索与回溯算法--递归
算法
风味蘑菇干24 分钟前
Stream基础题目
java·算法
KaMeidebaby35 分钟前
卡梅德生物技术快报|真核蛋白表达信号肽筛选实验全流程复盘
服务器·前端·数据库·人工智能·算法
霍霍的袁43 分钟前
【C++初阶】函数重载详细讲解
开发语言·c++·算法
心中有国也有家1 小时前
CANN 算子开发完全指南——从 TBE DSL 到算子上线全流程
人工智能·经验分享·笔记·分布式·算法
阿文的代码库1 小时前
线段树入门:算法分析
数据结构·算法