leetcode.90. 子集 II(python 3)

leetcode.90. 子集 II(python 3)

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]


做这道题之前先给大家介绍一个很牛皮的库:itertools,这个库或者说这个单词可能大家经常见到经常听到,但是不知道大家用的多不多。

直接见效果:

import itertools
  
# 所有情况(有序)
print list(itertools.permutations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
  
# 去重(无序)
print list(itertools.combinations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

那么我们这道题就很简单了:
上代码:

class Solution:
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        import itertools
        nums.sort()		# 刚开始没有排序,被[4,4,4,1,4]冷酷报错了
        my_set = set()
        for i in range(len(nums)):
            my_set.update(set(itertools.combinations(nums, i+1)))

        return list(my_set)+[[]]		# 幂集要包括空集

猜你喜欢

转载自blog.csdn.net/weixin_43944749/article/details/86666372