[LC] 90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res, lst = [], []
        if nums is None or len(nums) == 0:
            return res
        nums.sort()
        self.dfs(nums, 0, lst, res)
        return res
    
    def dfs(self, nums, level, lst, res):
        if level == len(nums):
            res.append(list(lst))
            return
        lst.append(nums[level])
        self.dfs(nums, level + 1, lst, res)
        lst.pop()

        # after adding the char, skip the following same one
        while level < len(nums) - 1 and nums[level] == nums[level + 1]:
            level += 1
        self.dfs(nums, level + 1, lst, res)
        

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/11711339.html
今日推荐