Generate all binary strings without consecutive 1 's | Java program to Generate all binary string without consecutive 1 's of size K ; Array conversion to String -- ; Base Condition when we reached at the end of Array * * ; Printing the Generated String * * Return to the previous case * ; If the first Character is Zero then adding * * ; If the Character is One then add Zero to next * * ; Calling Recursively for the next value of Array ; Initializing first character to Zero ; Generating Strings starting with Zero -- ; Initialized first Character to one -- ; Calling function fun with argument k ; This code is Contributed by Praveen Tiwari
import java . util . * ; import java . lang . * ; public class BinaryS { public static String toString ( char [ ] a ) { String string = new String ( a ) ; return string ; } static void generate ( int k , char [ ] ch , int n ) { if ( n == k ) { System . out . print ( toString ( ch ) + " ▁ " ) ; return ; } if ( ch [ n - 1 ] == '0' ) { ch [ n ] = '0' ; generate ( k , ch , n + 1 ) ; ch [ n ] = '1' ; generate ( k , ch , n + 1 ) ; } if ( ch [ n - 1 ] == '1' ) { ch [ n ] = '0' ; generate ( k , ch , n + 1 ) ; } } static void fun ( int k ) { if ( k <= 0 ) { return ; } char [ ] ch = new char [ k ] ; ch [ 0 ] = '0' ; generate ( k , ch , 1 ) ; ch [ 0 ] = '1' ; generate ( k , ch , 1 ) ; } public static void main ( String args [ ] ) { int k = 3 ; fun ( k ) ; } }