Subsets II

来源:互联网 发布:mac 搜狗不能使用 编辑:程序博客网 时间:2024/06/04 19:32

题目:

Given a collection of integers that might contain duplicates, nums, 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 nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

解题思路:

类似于1,只是加个set以去重。

class Solution:
    # @param {integer[]} nums
    # @return {integer[][]}
    def subsetsWithDup(self, nums):
        def convert_to_binary(n,limit):
            bi = []
            while (n>0):
                bi.append(n%2)
                n = n / 2
            if len(bi)<limit:
                bi += [0 for i in range(limit-len(bi))]
            return bi
        ans = []
        res = set()
        res.add(())
        length = len(nums)
        power = pow(2,length)
        for i in range(1,power):
            bi = convert_to_binary(i,length)
            tmp = []
            for index,x in enumerate(bi):
                if x==1:
                    tmp.append(nums[index])
            tmp.sort()
            res.add(tuple(tmp))
        for t in res:
            ans.append(list(t))
        return ans

0 0