90 Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note:The solution set must not contain duplicate subsets.

For example, If nums =[1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

The Idea: Implement the power set recursive formula, with the added benefit of ignoring duplicates. Duplicates can be used if we first sort the vector, and then append to an unordered_set. Sorting the vector essentially renders the ordering the vector obsolete, and the unordered_setavoids direct duplication.

The powerset begins with the empty set, and the build across each set by appending a character to end of each set.

case 1: {}                         = P(0) (empty set);      2^0 = 1
case 2: {}, {a}                    = P('a');                2^1 = 2
case n: {}, {a}, {b}, {ab}         = P('ab');               2^2 = 4

' '
' ' a 
' ' a b ab 
' ' a b ab c ac bc abc 
' ' a b ab c ac bc abc d ad bd abd cd acd bcd abcd

Complexity: O(n^2) time and space

Testing

Last updated

Was this helpful?