DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

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

SOLUTION:

class Solution:
    def gensets(self, nums, i, curr):
        if i == len(nums):
            self.subsets.add(tuple(curr))
            return
        self.gensets(nums, i + 1, curr)
        self.gensets(nums, i + 1, curr + [nums[i]])

    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        self.subsets = set()
        self.gensets(nums, 0, [])
        return list(self.subsets)
Enter fullscreen mode Exit fullscreen mode
Retry later

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay