Problem
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.
Algorithm
Using dfs to search the answer and use set to ignore the same data.
Code
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
if not nums:
return None
sLen = len(nums)
sort_nums = sorted(nums)
def list2str(s):
an = ''
for v in s:
an += str(v) + '#'
return an
def str2list(s):
if not s:
return []
an = []
sign = 1
v = 0
for c in s:
if c == '-':
sign = -1
elif c >= '0' and c <= '9':
v = v * 10 + ord(c) - ord('0')
else:
an.append(v * sign)
sign = 1
v = 0
return an
ans = set()
buf = []
visit = [0] * sLen
def C(n, cur):
ans.add(list2str(buf))
for i in range(cur, n):
if not visit[i]:
visit[i] = 1
buf.append(sort_nums[i])
C(n, i+1)
buf.pop()
visit[i] = 0
C(sLen, 0)
output = []
for s in ans:
output.append(str2list(s))
return output