Leetcode 90. Subsets II

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值