permutations(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, n));
Actually, this permutation algorithm is using the idea of
Switching current character with ith character.
Suppose we have a string abc
. So the permutation of it is:
abc, acb, bac, bca, cab, cba
We can find that the acb
is just switching b
and c
in abc
with prefix a
. And the bca
is just switching c
and a
in bac
with prefix b
.
Then we just use the same idea to recursively solve permutation problem.