How to use Recursion In Javascript
- We can recursively generate subsequences by including or excluding each character in the string.
- Create a function generateSubsequence with two parameters input and output.
- Check input.length==0 by using if condition.
- Here, value of inputString= “abc”.
- Then, call the function generateSubsequence.
Example: This example prints all subsequences of a string in JavaScript using the Recursion method.
function generateSubsequence(input, output)
{
// Base Case
if (input.length==0) {
console.log(output);
return;
}
// Include
generateSubsequence(
input.substring(1), output + input[0]);
// Exclude
generateSubsequence(
input.substring(1), output);
}
const inputString = 'abc';
generateSubsequence(inputString,"");
Output
abc ab ac a bc b c
JavaScript Program to Print all Subsequences of a String
A subsequence is a sequence that can be derived from another sequence by deleting zero or more elements without changing the order of the remaining elements. Subsequences of a string can be found with different methods here, we are using the Recursion method, Iteration method and Bit manipulation method.
Example: The example shows the input string and the corresponding output
Input: 'abc' Output: abc ab ac a bc b c
Table of Content
- Method 1: Using Recursion
- Method 2: Using Iteration
- Method 3: Using Bit Manipulation
- Method 4: Using Queue