您的位置:首页 > 编程语言 > Python开发

90. Subsets II Leetcode Python

2015-01-15 06:03 585 查看
Given a collection of integers that might contain duplicates, S, 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 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


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息