Problem
Given an array write an algorithm to get or print all the possible sub subsequences.
Examples
Example 1:
|
|
Solution
Method 1 - Bit manipulation and recursion
To generate all possible subsequences, we can use a recursive approach or an iterative approach using bit manipulation:
- Recursive Approach:
- For each element, we have two choices: either include the element in the current subsequence or exclude it.
- Recursively generate subsequences for both choices.
- Iterative Approach using Bit Manipulation:
- Each subsequence can be represented by a binary number where each bit represents whether the corresponding element is included in the subsequence.
- Iterate through all numbers from
0
to2^n - 1
(wheren
is the length of the array), and for each number, generate the subsequence corresponding to its binary representation.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n. 2^n)
, This is because there are (2^n) subsequences for an array of lengthn
, and generating each subsequence takesO(n)
time. - 🧺 Space complexity:
O(n. 2^n)
, for storing all subsequences.