Home / Data structures and Algorithms by Java Examples / Backtracking / Generating K-ary Strings using Recursion in JAVA Example
Generating K-ary Strings using Recursion in JAVA Example
1617 views.
GenerateKaryStrings.java
import java.util.Arrays;

class GenerateKaryStrings {
    static int[] arr;
    static void kString(int n, int k){
        //base case
        if (n == 0){
            System.out.println(Arrays.toString(arr));
        }
        else {
            //recursive case
            for (int j = 0; j < k; j++){
                arr[n-1] = j;
                kString(n-1,k);
            }
        }
    }
     
    public static void main(String[] args) {
        int n = 2;
        int k = 3;
         
        System.out.println("**Output**");
        arr = new int[n];
        kString(n,k);
    }
}
Output
**Output**
[0, 0]
[1, 0]
[2, 0]
[0, 1]
[1, 1]
[2, 1]
[0, 2]
[1, 2]
[2, 2]
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