原题
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
解法
DFS + 回溯法
代码
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(nums, index, path, res):
res.append(path)
for i in range(index, len(nums)):
if i > index and nums[i] == nums[i-1]:
continue
dfs(nums, i+1, path + [nums[i]], res)
res = []
nums.sort()
dfs(nums, 0, [], res)
return res
本文深入探讨了如何使用深度优先搜索(DFS)和回溯法解决包含重复元素的集合中所有可能子集的问题。通过具体实例[1,2,2],展示了如何避免生成重复的子集,并提供了详细的Python代码实现。
971

被折叠的 条评论
为什么被折叠?



