text: Generate all binary strings without consecutive 1 's | C ++ program to Generate all binary string without consecutive 1 's of size K ; A utility function generate all string without consecutive 1 'sof size K ; Print binary string without consecutive 1 's ; Terminate binary string ; If previous character is '1' then we put only 0 at end of string example str = "01" then new string be "010" ; If previous character is '0' than we put both '1' and '0' at end of string example str = "00" then new string "001" and "000" ; Function generate all binary string without consecutive 1 's ; Base case ; One by one stores every binary string of length K ; Generate all Binary string starts with '0' ; Generate all Binary string starts with '1' ; Driver program to test above function
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void generateAllStringsUtil ( int K , char str [ ] , int n ) { if ( n == K ) { str [ n ] = ' \0' ; cout << str << " ▁ " ; return ; } if ( str [ n - 1 ] == '1' ) { str [ n ] = '0' ; generateAllStringsUtil ( K , str , n + 1 ) ; } if ( str [ n - 1 ] == '0' ) { str [ n ] = '0' ; generateAllStringsUtil ( K , str , n + 1 ) ; str [ n ] = '1' ; generateAllStringsUtil ( K , str , n + 1 ) ; } } void generateAllStrings ( int K ) { if ( K <= 0 ) return ; char str [ K ] ; str [ 0 ] = '0' ; generateAllStringsUtil ( K , str , 1 ) ; str [ 0 ] = '1' ; generateAllStringsUtil ( K , str , 1 ) ; } int main ( ) { int K = 3 ; generateAllStrings ( K ) ; return 0 ; }