90. Subsets II Leetcode Python

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


  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值