Generate all the binary strings of N bits - GeeksforGeeks

12 Jul, 2021
Given a positive integer number N. The task is to generate all the binary strings of N bits. These binary strings should be in ascending order.Examples:  
Input: 2
Output:
0 0
0 1
1 0
1 1

Input: 3
Output:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
 
Approach: The idea is to try every permutation. For every position, there are 2 options, either ‘0’ or ‘1’. Backtracking is used in this approach to try every possibility/permutation. Below is the implementation of the above approach: 
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the above approach: #include <bits/stdc++.h>using namespace std; // Function to print the outputvoid printTheArray(int arr[], int n){    for (int i = 0; i < n; i++) {        cout << arr[i] << " ";    }    cout << endl;} // Function to generate all binary stringsvoid generateAllBinaryStrings(int n, int arr[], int i){    if (i == n) {        printTheArray(arr, n);        return;    }     // First assign "0" at ith position    // and try for all other permutations    // for remaining positions    arr[i] = 0;    generateAllBinaryStrings(n, arr, i + 1);     // And then assign "1" at ith position    // and try for all other permutations    // for remaining positions    arr[i] = 1;    generateAllBinaryStrings(n, arr, i + 1);} // Driver Codeint main(){    int n = 4;     int arr[n];     // Print all binary strings    generateAllBinaryStrings(n, arr, 0);     return 0;}
// Java implementation of the above approach:import java.util.*; class GFG{ // Function to print the outputstatic void printTheArray(int arr[], int n){    for (int i = 0; i < n; i++)    {        System.out.print(arr[i]+" ");    }    System.out.println();} // Function to generate all binary stringsstatic void generateAllBinaryStrings(int n,                            int arr[], int i){    if (i == n)    {        printTheArray(arr, n);        return;    }     // First assign "0" at ith position    // and try for all other permutations    // for remaining positions    arr[i] = 0;    generateAllBinaryStrings(n, arr, i + 1);     // And then assign "1" at ith position    // and try for all other permutations    // for remaining positions    arr[i] = 1;    generateAllBinaryStrings(n, arr, i + 1);} // Driver Codepublic static void main(String args[]){    int n = 4;     int[] arr = new int[n];     // Print all binary strings    generateAllBinaryStrings(n, arr, 0);}} // This code is contributed by// Surendra_Gangwar
# Python3 implementation of the# above approach # Function to print the outputdef printTheArray(arr, n):     for i in range(0, n):        print(arr[i], end = " ")         print() # Function to generate all binary stringsdef generateAllBinaryStrings(n, arr, i):     if i == n:        printTheArray(arr, n)        return         # First assign "0" at ith position    # and try for all other permutations    # for remaining positions    arr[i] = 0    generateAllBinaryStrings(n, arr, i + 1)     # And then assign "1" at ith position    # and try for all other permutations    # for remaining positions    arr[i] = 1    generateAllBinaryStrings(n, arr, i + 1) # Driver Codeif __name__ == "__main__":     n = 4    arr = [None] * n     # Print all binary strings    generateAllBinaryStrings(n, arr, 0) # This code is contributed# by Rituraj Jain
// C# implementation of the above approach:using System; class GFG{ // Function to print the outputstatic void printTheArray(int []arr, int n){    for (int i = 0; i < n; i++)    {        Console.Write(arr[i]+" ");    }    Console.WriteLine();} // Function to generate all binary stringsstatic void generateAllBinaryStrings(int n,                            int []arr, int i){    if (i == n)    {        printTheArray(arr, n);        return;    }     // First assign "0" at ith position    // and try for all other permutations    // for remaining positions    arr[i] = 0;    generateAllBinaryStrings(n, arr, i + 1);     // And then assign "1" at ith position    // and try for all other permutations    // for remaining positions    arr[i] = 1;    generateAllBinaryStrings(n, arr, i + 1);} // Driver Codepublic static void Main(String []args){    int n = 4;     int[] arr = new int[n];     // Print all binary strings    generateAllBinaryStrings(n, arr, 0);}} // This code has been contributed by 29AjayKumar
<?php// PHP implementation of the above approach // Function to print the outputfunction printTheArray($arr, $n){    for ($i = 0; $i < $n; $i++)    {        echo $arr[$i], " ";    }    echo "\n";} // Function to generate all binary stringsfunction generateAllBinaryStrings($n, $arr, $i){    if ($i == $n)    {        printTheArray($arr, $n);        return;    }     // First assign "0" at ith position    // and try for all other permutations    // for remaining positions    $arr[$i] = 0;    generateAllBinaryStrings($n, $arr, $i + 1);     // And then assign "1" at ith position    // and try for all other permutations    // for remaining positions    $arr[$i] = 1;    generateAllBinaryStrings($n, $arr, $i + 1);} // Driver Code$n = 4; $arr = array_fill(0, $n, 0); // Print all binary stringsgenerateAllBinaryStrings($n, $arr, 0); // This code is contributed by Ryuga?>
<script>    // Javascript implementation of the above approach:         // Function to print the output    function printTheArray(arr, n)    {        for (let i = 0; i < n; i++)        {            document.write(arr[i]+" ");        }        document.write("</br>");    }     // Function to generate all binary strings    function generateAllBinaryStrings(n, arr, i)    {        if (i == n)        {            printTheArray(arr, n);            return;        }         // First assign "0" at ith position        // and try for all other permutations        // for remaining positions        arr[i] = 0;        generateAllBinaryStrings(n, arr, i + 1);         // And then assign "1" at ith position        // and try for all other permutations        // for remaining positions        arr[i] = 1;        generateAllBinaryStrings(n, arr, i + 1);    }         let n = 4;       let arr = new Array(n);    arr.fill(0);       // Print all binary strings    generateAllBinaryStrings(n, arr, 0); // This code is contributed by divyeshrabadiya07.</script>
0 0 0 0 
0 0 0 1 
0 0 1 0 
0 0 1 1 
0 1 0 0 
0 1 0 1 
0 1 1 0 
0 1 1 1 
1 0 0 0 
1 0 0 1 
1 0 1 0 
1 0 1 1 
1 1 0 0 
1 1 0 1 
1 1 1 0 
1 1 1 1
 
Time complexity – O(2n)
Space complexity – O(n)
Related Article: Generate all the binary number from 0 to n 
rituraj_jain
ankthon
SURENDRA_GANGWAR
29AjayKumar
divyeshrabadiya07
abhinavjain194
binary-string
Backtracking
C++
Recursion
Recursion
Backtracking
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Subset Sum | Backtracking-4
m Coloring Problem | Backtracking-5
Hamiltonian Cycle | Backtracking-6
Print all permutations of a string in Java
Backtracking to find all subsets
Vector in C++ STL
Arrays in C/C++
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Socket Programming in C/C++