【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);
        }
    }
}
相关推荐
papership8 分钟前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_7968265211 分钟前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
山甫aa30 分钟前
差分数组 ----- 从零开始的数据结构
数据结构
早日退休!!!39 分钟前
《数据结构选型指南》笔记
数据结构·数据库·oracle
Beginner x_u1 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
丑八怪大丑1 小时前
Java数据结构与集合源码
数据结构
_深海凉_4 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
踩坑记录5 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎5 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰5 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习