【LeetCode 中等题】46-子集II

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

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

示例:

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

解法1。DFS的解法,还没理解

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        # import copy
        sub = []
        res = []
        nums.sort()
        self.helper(nums, 0, sub, res)
        return res
    
    def helper(self, nums, start, sub, res):
        res.append(sub[:])
        for i in range(start, len(nums)):
            if i == start or nums[i] != nums[i-1]:
                # tmp = copy.copy(nums[i])
                sub.append(nums[i])
                self.helper(nums, i+1, sub, res)
                sub.pop()

参考链接:https://www.cnblogs.com/mr-stn/p/8997775.html

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/85774156