(Any Language) Find all permutations of elements in a vector using swapping

旧巷老猫 提交于 2019-12-02 11:57:11

One way to do this is to, for the first character e:

  • First recurse on the next element
  • Then, for each element e2 after e:
    • Swap e and e2
    • Then recurse on the next element
    • And undo the swap

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!