How to generate permutations where a[i] != i?

后端 未结 6 580
野的像风
野的像风 2021-01-18 12:11

Suppose I have an array of integers int a[] = {0, 1, ... N-1}, where N is the size of a. Now I need to generate all permutations of

6条回答
  •  天命终不由人
    2021-01-18 12:52

    Just a hunch: I think lexicographic permutation might be possible to modify to solve this.

    Re-arrange the array 1,2,3,4,5,6,... by swapping pairs of odd and even elements into 2,1,4,3,6,5,... to construct the permutation with lowest lexicographic order. Then use the standard algorithm, with the additional constraint that you cannot swap element i into position i.

    If the array has an odd number of elements, you will have to make another swap at the end to ensure that element N-1 is not in position N-1.

提交回复
热议问题