90. Subsets II

Posted Premiumlab

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了90. Subsets II相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/subsets-ii/#/description

 

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: 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],
  []
]

 

 

Sol 1:

 

Iteration.

Sort first.

 

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        
        # iterately 
        res = [[]]
        nums.sort()
        for num in nums:
            res += [item + [num] for item in res if item + [num] not in res]
        return res

 

 

Sol 2:

 

DFS.

 

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        
        # DFS
        
        res = []
        nums.sort()
        self.dfs(nums, 0, [], res)
        return res
    
    def dfs(self, nums, index, path, res):
        res.append(path)
        for i in range(index, len(nums)):
            if i > index and nums[i] == nums[i-1]:
                continue
            self.dfs(nums, i+1, path+[nums[i]], res)

 

 

 

Similar question:

78. Subsets

 

以上是关于90. Subsets II的主要内容,如果未能解决你的问题,请参考以下文章

90. Subsets II

#Leetcode# 90. Subsets II

90. Subsets II

[LeetCode] 90. Subsets II 子集合 II

LeetCode 90:Subsets II

Leetcode 90. Subsets II