Home / Data structures and Algorithms by Java Examples / Backtracking / Generating Binary Strings using Recursion in JAVA Example
Generating Binary Strings using Recursion in JAVA Example
448 views.
GenerateBinaryStrings.java
import java.util.Arrays;

class GenerateBinaryStrings {
    static int[] arr;
    static void Binary(int n){
        //Base case
        if (n == 0){
            //Displays the array
            System.out.println(Arrays.toString(arr));
        }
        else {
            //Recursive case
            arr[n-1] = 0;
            Binary(n-1);
             
            arr[n-1] = 1;
            Binary(n-1);
        }
    }
     
    public static void main(String[] args) {
        int n = 2;
        
        arr = new int[n];
        Binary(n);
    }
}
Output: if n = 2
[0, 0]
[1, 0]
[0, 1]
[1, 1]
Output: if n = 3
[0, 0, 0]
[1, 0, 0]
[0, 1, 0]
[1, 1, 0]
[0, 0, 1]
[1, 0, 1]
[0, 1, 1]
[1, 1, 1]
Related Examples
   Generating Binary Strings using Recursion in JAVA Example
   Generating K-ary Strings using Recursion in JAVA Example
Copyright © 2016 Learn by Examples, All rights reserved