140 - 90 子集2

题目

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

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

示例:

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

解答

和子集1一样,在插入到res的时候做个判断就行了

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        res = []
        nums.sort()

        def helper(level, temp):
            res.append(temp)
            for i in range(level, len(nums)):
                if i > level and nums[i] == nums[i-1]:
                    continue
                helper(i+1, temp+[nums[i]])

        helper(0, [])
        return res

Runtime: 36 ms, faster than 97.11% of Python3 online submissions for Subsets II.

Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Subsets II.

if dRuntime: 56 ms, faster than 97.29% of JavaScript online submissions for Subsets II.

Memory Usage: 35.6 MB, less than 60.00% of JavaScript online submissions for Subsets II.

Runtime: 4 ms, faster than 81.58% of Go online submissions for Subsets II.

Memory Usage: 6.9 MB, less than 100.00% of Go online submissions for Subsets II.

Last updated

Was this helpful?