I've written the following code for returning an array of all permutations of a string. For long strings, will this lead to problems? I suspect for example that Java will not be able to use tail recursion, since the recursive call is not the last call of the function, which will possibly lead to stack overflow. Also, my solution collects all possible permutations and returns them in one single array. Since the number of permutations explodes with the length of the string, the array won't fit into memory for long strings. Can this be remedied somehow? Perhaps by using a Stream instead?
public static String[] perms(String str) {
String[] permutations = new String[factorial(str.length())];
int permIdx = 0;
if (str.length() == 1) {
return new String[]{str};
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
String restOfString = str.substring(0, i) + str.substring(i + 1);
String[] permutationsOfRestString = perms(restOfString);
for (String permutation : permutationsOfRestString) {
permutations[permIdx++] = ch + permutation;
}
}
return permutations;
}
public static int factorial(int n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(--n);
}
}