Print all possible strings of length k that can be formed from a set of n characters | GeeksforGeeks
Given a set of characters and a positive integer k, print all possible strings of length k that can be formed from the given set.
For a given set of size n, there will be n^k possible strings of length k. The idea is to start from an empty output string (we call it prefix in following code). One by one add all characters to prefix. For every character added, print all possible strings with current prefix by recursively calling for k equals to k-1. ==> In java, we should use List<String> or maybe StringBuilder, not use String.
Read full article from Print all possible strings of length k that can be formed from a set of n characters | GeeksforGeeks
Given a set of characters and a positive integer k, print all possible strings of length k that can be formed from the given set.
For a given set of size n, there will be n^k possible strings of length k. The idea is to start from an empty output string (we call it prefix in following code). One by one add all characters to prefix. For every character added, print all possible strings with current prefix by recursively calling for k equals to k-1. ==> In java, we should use List<String> or maybe StringBuilder, not use String.
// The method that prints all possible strings of length k. It is
// mainly a wrapper over recursive function printAllKLengthRec()
static
void
printAllKLength(
char
set[],
int
k) {
int
n = set.length;
printAllKLengthRec(set,
""
, n, k);
}
static
void
printAllKLengthRec(
char
set[], String prefix,
int
n,
int
k) {
// Base case: k is 0, print prefix
if
(k ==
0
) {
System.out.println(prefix);
return
;
}
// One by one add all characters from set and recursively
// call for k equals to k-1
for
(
int
i =
0
; i < n; ++i) {
// Next character of input added
String newPrefix = prefix + set[i];
// k is decreased, because we have added a new character
printAllKLengthRec(set, newPrefix, n, k -
1
);
}
}