This is some really confusing code, for two reasons:
- The
prefix
argument: you should call this function with an empty string in the first argument, for example permutations("", "ab")
to print all (both) permutations of "ab"
.
- The recursive call with
s.substring(0, i) + s.substring(i+1, n)
in the second argument: note that java's String.substring(x,y)
will not include the y-th character. So this amounts to passing s
with the y-th character deleted.
Now think what happens as you step through the for
loop: the first argument becomes ""
concatenated with "a"
, i.e. "a"
, and the second argument becomes s
with the first character deleted, i.e. "b"
. In the next recursive subcall, prefix
becomes "ab"
and the second argument becomes the empty string ""
. So the base-case n == 0
gets hit and we print the result "ab"
.
Now we go to the next iteration of the for loop, i == 1
. Now we pass "b"
in the first argument of our recursive subcall, and "a"
in the second argument. In the next recursive subcall prefix
becomes "ba"
and s.length
is 0, so base case again: print "ba"
.
It's clever, but inscrutable.