This is with respect to the problem, printing all permutations of a given string ABC. As far as I have understood, the program first prints ABC, then the string gets reset to ABC (which is the same as the first permutation of the string in this case) through backtracking, and then when i=1 and j=2, letters B and C are swapped, following which i gets incremented to 2 and is passed to the permute function where the second permutation ACB is printed on the screen. Following this, backtracking again takes place and we get back ABC.
I'm unable to understand how the next permutation BAC gets printed. For this the value of i would have to be reset to 0 (previously i=2 when we print out ACB) and the value of j should equal 1. (previously j=2 when the swapping of B and C takes place). How does i=0 and j=1, when there is no line of code in this program that does the same?
P.S: The code works fine, but I'm unable understand why it works the way it works. If anyone could trace the code step by step for each permutation it prints on the screen, that would be really helpful!
Here is the code:
void permute(String s, int i=0){
if(i==s.length()-1){
System.out.println(s);
return;
}
for(int j=i; j<s.length(); j++){
swap(s[i], s[j]);
permute(s, i+1);
swap(s[i], s[j]);
}
}