Subsets II

Backtracking

Problem

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.

For example:

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

Thought Process

  • Question is vey similar to the original Subset problem with one difference, there are duplicate numbers in the list

  • To handle the duplicate numbers, we will sort the numbers first and skip any numbers that are the same as the previous one

Solution

Key Points

  • To handle the case of some duplicate subsets due to repeated elements, we will sort the input list and in our for loop we will check if nums[i] == nums[i-1] and continue if this is true, because since we already came across that same element previously and recorded the subsets, we don't want to do it again

Time Complexity

  • Time: O(n2n)O(n * 2^n)

  • Space:O(n2n)O(n * 2^n)

Last updated

Was this helpful?