Generate n-Length K-ary String
Table of contents
Problem
Generate all possible n-length k-ary strings.
K-ary string is a string that only contains characters from the set $\{0, 1, \ldots, k-1\}$.
Backtracking
- Create an array
arr
of lengthn
, initialized with all zeros. - Have a helper function that wil print the array
arr
as a single string. - In the recursion:
void generate(int[] arr, int n, int k) {
if (n < 1) {
printArray(arr);
} else {
for (int i = 0; i < k; i++) {
arr[n - 1] = i;
generate(arr, n - 1, k);
}
}
}
The idea is to fix a single character at a time, and recursively generate all possible strings with the fixed character.
Once all possibilities with the fixed character are exhausted, we move on to experiment with another character.
The recurrence relation is
\[T(n) = k T(n - 1) + O(n)\]which is $O(k^n) \cdot O(n)$.
The $O(n)$ comes from naively printing the array as a string.