【陪伴式刷题】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)
相关推荐
一定要AK7 小时前
Spring 入门核心笔记
java·笔记·spring
A__tao7 小时前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
KevinCyao8 小时前
java视频短信接口怎么调用?SpringBoot集成视频短信及回调处理Demo
java·spring boot·音视频
迷藏4948 小时前
**发散创新:基于Rust实现的开源合规权限管理框架设计与实践**在现代软件架构中,**权限控制(RBAC)** 已成为保障
java·开发语言·python·rust·开源
skywalker_118 小时前
力扣hot100-3(最长连续序列),4(移动零)
数据结构·算法·leetcode
6Hzlia8 小时前
【Hot 100 刷题计划】 LeetCode 17. 电话号码的字母组合 | C++ 回溯算法经典模板
c++·算法·leetcode
wfbcg9 小时前
每日算法练习:LeetCode 209. 长度最小的子数组 ✅
算法·leetcode·职场和发展
_日拱一卒9 小时前
LeetCode:除了自身以外数组的乘积
数据结构·算法·leetcode
wuxinyan1239 小时前
Java面试题47:一文深入了解Nginx
java·nginx·面试题
新知图书9 小时前
搭建Spring Boot开发环境
java·spring boot·后端