Subsets

Given a set of integers, return all possible subsets of the given set.

The solution set cannot contain duplicate subsets. How large is the set? less than 15 elements Does the set contain duplicates? nope Positive and negative? both

Example

I: [1,2,3]
O: [ [],
     [1], [2], [3], 
     [1,2], [1,3],
     [2,3],
     [1,2,3]
   ]

Exhaustive Search (prefix tree)

Starting from an empty set and recording all the states to enumerate the set.

Define Recursion
genSubsets(List<List<Integer>> results, int[] nums, List<Integer> subset, int startIndex)
startIndex is a starting node for this depth first search
Add all susbets starting with startIndex with subset as prefix to results

Recursive Calls
for i from startIndex to n-1
    genSubsets(results, nums, new subset.add(i), i+1)

Base Case
if startIndex = n: results.add(new subset)

Code

How do we only display the second level [1,3], [2,3], [1,2]?

Exhaustive Search (decision tree)

We can either include or disinclude an element.

Code

Java

Python

Do it iteratively

Binary Number

We can see how each element is either included or disinclined in a subset. This is kind of binary property to make us wonder if there's a solution with bit manipulation. We can observe the formulation from this example.

Code

Time Complexity

#subproblems * time/subproblem = 2^n * O(n) = O(n*2^n)

What if the input has duplicates?

Example

Analysis

The easiest and space-costly way would be having a hashset to store all the subsets that are visited. But can we prune some repetitive subtrees?

Prune Decision Tree

Now we need to sort the input.

Prune Prefix Tree

So the key is i > startIndex && nums[i] == nums[i-1]. Since we already sorted nums in this case, we can skip duplicates by checking current_element == previous_element. Also i > startIndex guarantees that this is not the first iteration in the current loop.

Last updated