题目链接
https://leetcode.com/problems/subsets-ii/
题目原文
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
题目大意
给出一个有重复元素的所有集合的子集的list
解题思路
使用dfs进行求解
代码
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(depth, start, valuelist):
if valuelist not in ans:
ans.append(valuelist)
if depth == len(nums):
return
for i in range(start, len(nums)):
dfs(depth + 1, i + 1, valuelist + [nums[i]])
nums.sort()
ans = []
dfs(0, 0, [])
return ans