LeetCode 题解工作台
子集 II
给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的 子集 (幂集)。 解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。 示例 1: 输入: nums = [1,2,2] 输出: [[],[1],[1,2],[1,2,2],[2],[2,2]] 示例 2…
3
题型
8
代码语言
3
相关题
当前训练重点
中等 · 回溯·pruning
答案摘要
我们可以先对数组 进行排序,方便去重。 然后,我们设计一个函数 ,表示当前从第 个元素开始搜索子集。函数 的执行逻辑如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 回溯·pruning 题型思路
题目描述
给你一个整数数组 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
解题思路
方法一:排序 + DFS
我们可以先对数组 进行排序,方便去重。
然后,我们设计一个函数 ,表示当前从第 个元素开始搜索子集。函数 的执行逻辑如下:
如果 ,说明已经搜索完所有元素,将当前子集加入答案数组中,递归结束。
如果 ,将第 个元素加入子集,执行 ,然后将第 个元素从子集中移除。接下来,我们判断第 个元素是否和下一个元素相同,如果相同,则循环跳过该元素,直到找到第一个和第 个元素不同的元素,执行 。
最后,我们只需要调用 ,返回答案数组即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.