LeetCode 题解工作台
子集
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的 子集 (幂集)。 解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。 示例 1: 输入: nums = [1,2,3] 输出: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] …
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 回溯·pruning
答案摘要
我们设计一个函数 ,表示从数组的第 个元素开始搜索所有子集。函数 的执行逻辑如下: - 如果 ,表示当前已经搜索结束,将当前得到的子集 加入答案数组 中,然后返回;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 回溯·pruning 题型思路
题目描述
给你一个整数数组 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] <= 10nums中的所有元素 互不相同
解题思路
方法一:DFS(回溯)
我们设计一个函数 ,表示从数组的第 个元素开始搜索所有子集。函数 的执行逻辑如下:
- 如果 ,表示当前已经搜索结束,将当前得到的子集 加入答案数组 中,然后返回;
- 否则,我们可以选择不选择当前元素,直接执行 ;也可以选择当前元素,即把当前元素 加入子集 ,然后执行 ,注意要在执行 以后再将 从子集 中移除(回溯)。
在主函数中,我们调用 ,即从数组的第一个元素开始搜索所有子集。最后返回答案数组 即可。
时间复杂度 ,空间复杂度 。其中 为数组的长度。一共有 个子集,每个子集需要 的时间来构造。
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def dfs(i: int):
if i == len(nums):
ans.append(t[:])
return
dfs(i + 1)
t.append(nums[i])
dfs(i + 1)
t.pop()
ans = []
t = []
dfs(0)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | \mathcal{O}(N \times 2^N) |
| 空间 | \mathcal{O}(N) |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates familiarity with backtracking techniques and pruning strategies.
- question_mark
Candidate handles edge cases such as small arrays or empty sets.
- question_mark
Candidate optimizes the solution and considers different approaches like bit manipulation or iterative methods.
常见陷阱
外企场景- error
Failing to prune unnecessary recursive calls, leading to duplicate subsets.
- error
Incorrectly handling the base case or recursion termination, which can result in incomplete subsets.
- error
Overcomplicating the problem by not leveraging simpler iterative or bit manipulation techniques.
进阶变体
外企场景- arrow_right_alt
Allow subsets to include duplicate elements.
- arrow_right_alt
Return the subsets sorted or in a specific order.
- arrow_right_alt
Implement a solution using dynamic programming or memoization.