![]() |
VOOZH | about |
Given an integer n, the task is to generate all binary strings of size n without consecutive 1's.
Examples:
Input : n = 4
Output : 0000 0001 0010 0100 0101 1000 1001 1010Input : n = 3
Output : 000 001 010 100 101
Approach:
The idea is to generate all binary strings of length n without consecutive 1's using a recursive backtracking approach that explores all valid configurations. We start with a string of all '0's and then recursively consider two options for each position: either keep it as '0' or change it to '1'. When we place a '1' at any position, we skip the next position in our recursive exploration to ensure we don't create consecutive 1's.
Step by step approach:
0000 0001 0010 0100 0101 1000 1001 1010
Interesting Fact : The count of n length strings with no consecutive 1s is equal to (n+2)-th Fibonacci Number
Time Complexity: O(n 2^n), as at each step, we can consider 0 or 1. Please note that this is an upper bound. An exact bound would be O(n F(n+2)) where F(n+2) is (n+2)th Fibonacci Number.
Auxiliary Space: O(n) due to recursion call stack.