【陪伴式刷题】Day 24|回溯|78.子集(Subsets)

刷题顺序按照代码随想录建议

题目描述

英文版描述

Given an integer array nums of unique elements, return all possible

subsets

(the power set) .

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

Input: nums = 1,2,3 Output: \[,1,2,1,2,3,1,3,2,3,1,2,3]

Example 2:

Input: nums = 0 Output: \[,0]

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All the numbers of nums are unique.

英文版地址

leetcode.com/problems/su...

中文版描述

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

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

示例 1:

输入: nums = 1,2,3 输出: \[,1,2,1,2,3,1,3,2,3,1,2,3]

示例 2:

输入: nums = 0 输出: \[,0]

提示:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • nums 中的所有元素 互不相同

中文版地址

leetcode.cn/problems/su...

解题方法

递归法

java 复制代码
class Solution {
   List<List<Integer>> result = new ArrayList<>();
    List<Integer> level = new ArrayList<>();

    /**
     * 给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
     * 解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
     * <p>
     * 示例 1:
     * 输入:nums = [1,2,3]
     * 输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> subsets(int[] nums) {
        backTracking(nums, 0);
        return result;
    }

    private void backTracking(int[] nums, int startIndex) {
        result.add(new ArrayList<>(level));
    
        for (int i = startIndex; i < nums.length; i++) {
            level.add(nums[i]);
            backTracking(nums, i + 1);
            level.remove(level.size() - 1);
        }
    }
}

复杂度分析

  • 时间复杂度:O(n×2^n),一共 2^n个状态,每种状态需要 O(n)的时间来构造子集
  • 空间复杂度:O(n),临时List的空间代价是 O(n),递归时栈空间的代价为 O(n)
相关推荐
用户4682557459135 分钟前
Testcontainers 在 Windows Docker Desktop 上跑不通:协议层不兼容 + 4 种可行环境
java·后端
程序员小羊!27 分钟前
12.Java 多线程编程
java·开发语言
xuhaoyu_cpp_java33 分钟前
项目学习(三)代码生成器
java·经验分享·笔记·学习
乐观勇敢坚强的老彭33 分钟前
C++信息学奥赛lesson1
java·开发语言·c++
San813_LDD38 分钟前
[深度学习] 数据序列化格式对比:以日志级别配置为例
xml·java·前端
github_czy42 分钟前
更加优雅的类型检查与传参---mcp源码分析
java·服务器·开发语言
专注_每天进步一点点1 小时前
IDEA中,Apifox Helper 的 2.0.15-243版本的插件 导出指定的接口,入参的中文名为空,描述为空
java·ide·intellij-idea
兰令水1 小时前
leecodecode【区间DP+树形DP】【2026.6.10打卡-java版本】
java·算法·leetcode
小刘|1 小时前
Spring WebFlux + AI 流式输出深度解析:Spring AI 与 LangChain4j 效果差异溯源
java·后端·spring
Arvin.Angela1 小时前
Maven 的基本配置操作
java·maven