Subsets ii

class Solution:
    def __init__(self):
        self.res = []
        self.path = []
        self.used = []

    def backtrack(self, nums, startIndex):
        self.res.append(self.path.copy())
        for i in range(startIndex, len(nums)):
            if i > 0 and nums[i - 1] == nums[i] and self.used[i - 1] == False:
                continue
            self.path.append(nums[i])
            self.used[i] = True

            self.backtrack(nums, i + 1)

            self.used[i] = False
            self.path.pop()

    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        self.used = [False] * len(nums)

        self.backtrack(nums, 0)


        return self.res

Subsets II

Difficulty: Medium


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