![]() |
VOOZH | about |
Given a string s of size n (1 ≤ n ≤ 20), the task is to print all subsequences of string. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Examples:
Input: s = "abc"
Output: ["", "a", "b", "c", "ab", "ac", "bc", "abc"]
Explanation: All possible combinations of the characters in the string are returned, including the empty string.
Input: S = "ab"
Output: ["", "a", "b", "ab"]
Explanation: All subsequences of the string ab are returned in any order.
Table of Content
The recursive approach works by considering two options for each character:
By recursively generating subsequences for all characters, we can obtain the complete set of subsequences.
['abc', 'ab', 'ac', 'a', 'bc', 'b', 'c', '']
Time Complexity: O(n * 2^n), where n is length of the string. At each step we make two recursive calls resulting in 2^n subsequences.
Auxiliary Space: O(2^n) for storing all subsequences and O(n) recursion stack.
The iterative approach uses bit masking to generate all subsequences. Each bit in a number represents whether a character is included in the subsequence.
How it Works:
['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
Time Complexity: O(n * 2^n), where 2^n is the number of subsequences and n is the maximum length of each subsequence.
Auxiliary Space: O(2^n), as all subsequences are stored in a list.
Using itertools.combinations library we can generate all subsequences of lengths 0 to n.
['', 'a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
Time Complexity: O(n * 2^n), as it generates all subsets.
Auxiliary Space: O(2^n), as all subsequences are stored.