90. Subsets II

90. Subsets II

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

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

Example 2:

Input: nums = [0]
Output: [[],[0]]

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10

 

For every number in nums, we add it to every i in res. Ex. [[]], we add [] + [1] to res. The new res is [ [], [1] ]. Then add [] + [2] and [1] + [2], the new res is [[],[1],[2],[1,2]].

To void the duplicate, we check if i + [num] is already in res. So the iterate solution for Subsets II is:

def subsetsWithDup(self, nums):
    res = [[]]
    nums.sort()
    for num in nums: 
        res += [ i + [num] for i in res if i + [num] not in res]
    return res

 

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        length = len(nums)
        if length == 0:
            return [[]]
       
        results = [[]]
        nums.sort()
        for num in nums:
            results = results + [ [num] + i for i in results if [num] + i not in results]
       
        return results
No Comments

Post A Comment