Print All N Length Strings from Given Number K

Objective: Given Number K, Print all the strings of N length.

Example:

N = 2, K = 3

[1, 1] [2, 1] [3, 1] [1, 2] [2, 2] [3, 2] [1, 3] [2, 3] [3, 3]

Approach:

This problem is quite similar to Print All Subsets of a given set and Print All Combinations of subset of size K from Given Array

  • Loop through i = 1 to K.
  • Add i to the result Array, which is the size N and make a recursive call to (N-1).
  • Base case: when n becomes 0 (means array is full).
  • See the code for better explanation.

Code:


import java.util.*;
public class NLengthStringFromKNumbers {
public void print(int n, int k, int[] A) {
if (n <= 0) {
System.out.println(Arrays.toString(A));
} else {
for (int i = 1; i <= k; i++) {
A[n 1] = i;
print(n 1, k, A);
}
}
}
public static void main(String[] args) {
int n = 2;
int k = 3;
NLengthStringFromKNumbers i = new NLengthStringFromKNumbers();
i.print(n, k, new int[n]);
}
}

Output:
[1, 1]
[2, 1]
[3, 1]
[1, 2]
[2, 2]
[3, 2]
[1, 3]
[2, 3]  

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.