Problem
Given a set of distinct integers/characters, S, return all possible subsets.
OR
Given an integer array
nums
of unique elements, return all possible subsets (the power set).
Examples
If we’re given a set of integers such that S = {1, 2, 3}, how can we find all the subsets of that set? For example, given S, the set of all subsets i.e. P(S) we get are {}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, and {1, 2, 3}. Here is {} is empty set denoted by Φ.
Example 1:
|
|
Example 2:
|
|
Follow up - Subsets II
Definition
Subarrays vs Subsequences vs Subsets Definition
Solution
If S has n elements in it then P(s) will have 2^n elements. P(S) is also called power set.
Method 1 - Use Backtracking
This can be solved in couple of ways using recursion, backtracking. This is similar to Print All Combinations of subset of size K from Given Array.
At each index in input array, we have to choose whether we have to choose a number or not.
Video Explanation
Here is the video explanation:
Thought Process 1 - Focus One Element at Each Level
Each recursion level focuses on one element, we need to decide choose or not choose this element. (Every level split into 2 branches.)
|
|
Thought Process 2 - Focus on All the Following Elements at Each Level
Each recursion level focuses on all the following elements. We scan through all the following elements and decide whether to choose or not choose that element. (Every level split into N branches.)
|
|
Complexity
- ⏰ Time complexity:
O(n.2^n)
(as we are taking call between 2 (yes or no) paths for n elements)
Method 2 - Using Bit Manipulation and Iterative
We know total number of sets is 2^n. We can loop through each solution from 0 to 2^n - 1. For each case, we add a value or not.
Example
Consider the set:
A = {a, b, c}
So, we need 3 bits, and 2^3 answers:
$$0 = (000)_2 = {}$$ $$1 = (001)_2 = {c}$$ $$2 = (010)_2 = {b}$$ $$3 = (011)_2 = {b, c}$$ $$4 = (100)_2 = {a}$$ $$5 = (101)_2 = {a, c}$$ $$6 = (110)_2 = {a, b}$$ $$7 = (111)_2 = {a, b, c}$$
Pseudocode
|
|
Code
|
|
|
|
|
|