Generating all possible Subsequences using Recursion
Given an array. The task is to generate and print all of the possible subsequences of the given array using recursion.
Examples:
Input : [1, 2, 3] Output : [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3] Input : [1, 2] Output : [2], [1], [1, 2]
Approach: For every element in the array, there are two choices, either to include it in the subsequence or not include it. Apply this for every element in the array starting from index 0 until we reach the last index. Print the subsequence once the last index is reached.
Below diagram shows the recursion tree for array, arr[] = {1, 2}.

Below is the implementation of the above approach.
# Python3 code to print all possible # subsequences for given array using # recursion # Recursive function to print all # possible subsequences for given array def printSubsequences(arr, index, subarr): # Print the subsequence when reach # the leaf of recursion tree if index == len(arr): # Condition to avoid printing # empty subsequence if len(subarr) != 0: print(subarr) else: # Subsequence without including # the element at current index printSubsequences(arr, index + 1, subarr) # Subsequence including the element # at current index printSubsequences(arr, index + 1, \ subarr+[arr[index]]) return arr = [1, 2, 3] printSubsequences(arr, 0, []) |
[3] [2] [2, 3] [1] [1, 3] [1, 2] [1, 2, 3]
Time Complexity: ![]()
Recommended Posts:
- Generating subarrays using recursion
- Generating random Id's in Python
- Generating Lyndon words of length n
- Generating Word Cloud in Python | Set 2
- Generating numbers that are divisor of their right-rotations
- Subset array sum by generating all the subsets
- Generating Strong Password using Python
- Generating Word Cloud in Python
- Generating Random id's using UUID in Python
- Generating random number list in Python
- Reading and Generating QR codes in Python using QRtools
- Generating random strings until a given string is generated
- Generating hash id's using uuid3() and uuid5() in Python
- Sum of all subsequences of an array
- Number of Subsequences with Even and Odd Sum
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



