I was asked this question in a Lab session today.
We can imagine a vector containing the elements 1 ... N - 1, with a length N. Is there an algorithmic (systematic) meth
One way to do this is to, for the first character e
:
e2
after e
:
e
and e2
Pseudo-code:
permutation(input, 0)
permutation(char[] array, int start)
if (start == array.length)
print array
for (int i = start; i < array.length; i++)
swap(array[start], array[i])
permutation(array, start+1)
swap(array[start], array[i])
With the main call of this function, it will try each character in the first position and then recurse. Simply looping over all the characters works here because we undo each swap afterwards, so after the recursive call returns, we're guaranteed to be back where we started.
And then, for each of those recursive calls, it tries each remaining character in the second position. And so on.
Java live demo.