LeetCode 题解工作台

子集 II

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的 子集 (幂集)。 解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。 示例 1: 输入: nums = [1,2,2] 输出: [[],[1],[1,2],[1,2,2],[2],[2,2]] 示例 2…

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 回溯·pruning

bolt

答案摘要

我们可以先对数组 进行排序,方便去重。 然后,我们设计一个函数 ,表示当前从第 个元素开始搜索子集。函数 的执行逻辑如下:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 回溯·pruning 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的 子集(幂集)。

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

 

示例 1:

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

示例 2:

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

 

提示:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
lightbulb

解题思路

方法一:排序 + DFS

我们可以先对数组 nums\textit{nums} 进行排序,方便去重。

然后,我们设计一个函数 dfs(i)\textit{dfs}(i),表示当前从第 ii 个元素开始搜索子集。函数 dfs(i)\textit{dfs}(i) 的执行逻辑如下:

如果 ini \geq n,说明已经搜索完所有元素,将当前子集加入答案数组中,递归结束。

如果 i<ni < n,将第 ii 个元素加入子集,执行 dfs(i+1)\textit{dfs}(i + 1),然后将第 ii 个元素从子集中移除。接下来,我们判断第 ii 个元素是否和下一个元素相同,如果相同,则循环跳过该元素,直到找到第一个和第 ii 个元素不同的元素,执行 dfs(i+1)\textit{dfs}(i + 1)

最后,我们只需要调用 dfs(0)\textit{dfs}(0),返回答案数组即可。

时间复杂度 O(n×2n)O(n \times 2^n),空间复杂度 O(n)O(n)。其中 nn 是数组 nums\textit{nums} 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        def dfs(i: int):
            if i == len(nums):
                ans.append(t[:])
                return
            t.append(nums[i])
            dfs(i + 1)
            x = t.pop()
            while i + 1 < len(nums) and nums[i + 1] == x:
                i += 1
            dfs(i + 1)

        nums.sort()
        ans = []
        t = []
        dfs(0)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Ability to manage duplicate subsets effectively is key to solving this problem.

  • question_mark

    Understanding backtracking with pruning demonstrates good problem-solving skills.

  • question_mark

    Familiarity with subset generation, recursive exploration, and skipping duplicates is crucial.

warning

常见陷阱

外企场景
  • error

    Forgetting to skip duplicate elements leads to redundant subsets being included in the final result.

  • error

    Not sorting the input array can make it difficult to recognize and skip duplicates.

  • error

    Failing to prune the recursive tree efficiently can lead to unnecessary computations.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling arrays of varying sizes up to 10 elements with more complex duplicates.

  • arrow_right_alt

    Adapting the approach for larger datasets that might not fit in memory or have different constraints.

  • arrow_right_alt

    Modifying the solution to generate subsets of a specific size or meet additional requirements.

help

常见问题

外企场景

子集 II题解:回溯·pruning | LeetCode #90 中等