How to useRecursive Function in Javascript
Here, the recursive function generates all the binary strings of the input size ‘K’ without consecutive 1’s by actually appending the ‘0’ and the ‘1’ to the input string ‘str’. In each step there, is the appending of 0 or 1, and the binary strings are stored in the res variable and printed using the log function.
Example: In this example, we will Generate all binary strings without consecutive 1’s in JavaScript using the Recursive Function.
let K = 5;
let res = "";
function binaryStr(str, n) {
if (n === K) {
res += str + " ";
return;
}
if (n === 0 || str[n - 1] === "0") {
binaryStr(str + "0", n + 1);
binaryStr(str + "1", n + 1);
} else {
binaryStr(str + "0", n + 1);
}
}
// Strings starting with 0
binaryStr("0", 1);
// Strings starting with 1
binaryStr("1", 1);
console.log(res.trim());
Output
00000 00001 00010 00100 00101 01000 01001 01010 10000 10001 10010 10100 10101
JavaScript Program to Generate all Binary Strings Without Consecutive 1’s
Given an integer, K. Generate all binary strings of size k without consecutive 1’s.
Examples:
Input : K = 3
Output : 000 , 001 , 010 , 100 , 101
Input : K = 4
Output: 0000 0001 0010 0100 0101 1000 1001 1010
Table of Content
- Approach 1: Using Recursive Function
- Approach 2: Using Stack Data Structure
- Approach 3: Using Iteration and padStart() Method
- Approach 4: Using Backtracking
So, let’s see each of the approaches with its practical implementation.