【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 numsi \le 10 −10≤numsi≤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);
        }
    }
}
相关推荐
间歇性努力持续性发呆的野生快乐选手17 分钟前
栈的性质(进栈,出栈,访问)
数据结构·c++
m0_5474866633 分钟前
《数据结构与算法》全套PPT课件2026(中国海洋大学)
数据结构·算法
旖旎夜光43 分钟前
LeetCode 904:水果成篮(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
怪奇云呼军1 小时前
G.711、Opus 和重采样会拖慢识别吗?闪电智能VoiceAgent 的音频入口怎么选
java·人工智能·python·算法·云计算·音视频
ZC跨境爬虫1 小时前
LeetCode 27. 移除元素(双指针详解 + Java Python 多解法对比)
java·python·leetcode
乐观勇敢坚强的老彭2 小时前
C++ 竞赛常用算法模板速查表
开发语言·c++·算法
高洁012 小时前
工信部教考中心证书
人工智能·深度学习·算法·机器学习·知识图谱
我变成萤火虫3 小时前
河南萌新联赛2026第(三)场:郑州轻工业大学
数据结构·c++·算法·贪心算法·stl·深度优先·哈希算法
Dr.kangder3 小时前
嵌入式面试总结(十九)——内存泄露
单片机·算法·面试·职场和发展·架构·硬件架构
白狐_7983 小时前
408数据结构第7章:B树①——基础概念与结构
数据结构·b树