【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);
        }
    }
}
相关推荐
剪一朵云爱着8 小时前
力扣81. 搜索旋转排序数组 II
算法·leetcode·职场和发展
报错小能手10 小时前
刷题日常 5 二叉树最大深度
算法
码银11 小时前
【数据结构】顺序表
java·开发语言·数据结构
Greedy Alg11 小时前
LeetCode 84. 柱状图中最大的矩形(困难)
算法
im_AMBER11 小时前
Leetcode 52
笔记·学习·算法·leetcode
小欣加油11 小时前
leetcode 946 验证栈序列
c++·算法·leetcode·职场和发展
包饭厅咸鱼11 小时前
PaddleOCR----制作数据集,模型训练,验证 QT部署(未完成)
算法
无敌最俊朗@12 小时前
C++ 并发与同步速查笔记(整理版)
开发语言·c++·算法
王哈哈^_^12 小时前
【完整源码+数据集】课堂行为数据集,yolo课堂行为检测数据集 2090 张,学生课堂行为识别数据集,目标检测课堂行为识别系统实战教程
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计