I have found the following Java code. It counts all the permutations of a string. However, I can't understand what it does inside the for loop of the permutation method. More specifically I can't understand the purpose of the rem string and the recursive call.
Is there any thoughts on this?
Thanks.
void permutaion(String str){
permutaion(str,"");
}
void permutaion(String str, String prefix){
if(str.length() == 0){
System.out.println(prefix);
} else{
for(int i=0; i < str.length(); i++){
String rem = str.substring(0,i) + str.substring(i+1);
permutaion(rem, prefix + str.charAt(i));
}
}
}
You should run this code by hand on paper to see it's magic and understand it :)
The recursive on permutation function is for permutation input string, and the for loop is for all possible case. The prefix is the permutation of the input string when a recursive finish.
The basic idea is this: to get the permutations of a given N-character string you: