Description
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Constraints:
• 1 <= nums.length <= 10
• -10 <= nums[i] <= 10
Example
Example 1:
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Submissions
解题思路先排序,否则对顺序不敏感就会造成重复。然后进行深度优先搜索,没有终止条件,同一个位置上,出现过的数字就直接跳过。其中dfs()函数,就是在当前index元素使用的情况下,从nums的index后面抽取0个或者全部数字放入path的后面。注意这个for循环,意义是当前元素如果使用,后面的那个元素从哪里开始,也就决定了后面的数字选择多少个。
实现代码如下:
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
self.dfs(nums, 0, res, [])
return res
def dfs(self, nums, index, res, path):
if path not in res:
res.append(path)
for i in range(index, len(nums)):
if i > index and nums[i] == nums[i - 1]:
continue
self.dfs(nums, i + 1, res, path + [nums[i]])