leetcode90 -- Subsets II

leetcode90 -- 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:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        
        res = [[]]
        nums.sort()
        
        for i in range(len(nums)):
            m = len(res)
            for j in range(m):
                temp = res[j][:]
                temp.append(nums[i])
                if temp not in res:
                    res.append(temp)
                    
        return res

打赏,谢谢~~

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,多谢支持~

打开微信扫一扫,即可进行扫码打赏哦