Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
For example,
If S = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
算法NP hard T(n) = n * T(n-1)
这道题目的解法和大部分的求combination和subset的方法一样,在递归中加一个循环逐次加入新的元素。
这道题目看似O(n^2)起始不然,随着数组的增大子集的数量是factorial 增长的。
This problem can be solve with adding one iteration in recursion. and append the subsets to the solution list. The time complexity is NP hard, because the number of sub array is factorial related with the size of the array.
class Solution:
# @param num, a list of integer
# @return a list of lists of integer
def bfs(self,valuelist,solution,S,start):
if valuelist not in solution and len(valuelist)<=len(S):
solution.append(valuelist)
for index in range(start,len(S)):
valuelist=valuelist+[S[index]]
self.bfs(valuelist,solution,S,index+1)
valuelist=valuelist[:len(valuelist)-1]
def subsetsWithDup(self, S):
solution=[]
if len(S)==0:
return solution
S.sort()
self.bfs([],solution,S,0)
return solution
Simplified version
class Solution:
# @param num, a list of integer
# @return a list of lists of integer
# a dfs problem
def dfs(self, res, val, num, start):
if val not in res:
res.append(val)
for i in range(start, len(num)):
self.dfs(res, val+[num[i]], num, i+1)
def subsetsWithDup(self, S):
res = []
if len(S) == 0:
return res
S.sort()
val = []
self.dfs(res, val, S, 0)
return res