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

后端 未结 1 996
时光说笑
时光说笑 2021-01-29 02:44

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

1条回答
  •  醉梦人生
    2021-01-29 03:20

    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.

    0 讨论(0)
提交回复
热议问题