Prev/Next Permutation

Example

For[1,3,2,3], the previous permutation is[1,2,3,3]

For[1,2,3,4], the previous permutation is[4,3,2,1]

[1, 2, 2, 1, 1, 3, 3, 4, 5] prev [1, 2, 1, 5, 4, 3, 3, 2, 1]

For[1,3,2,3], the next permutation is[1,3,3,2]

For[4,3,2,1], the next permutation is[1,2,3,4]

[1, 2, 1, 5, 4, 3, 3, 2, 1] next [1, 2, 2, 1, 1, 3, 3, 4, 5]

Note

迭代法求全排列的主要组成部分

previous:

  • 1234之前是4321,所以保证之后部分递,找到转折点index,转折数index - 1

  • 找到转折点之后的最后一个比转折数的数,交换它们

  • 对index到最后递增的子数组进行反转

122113345 --> 121123345 --> 121543321

next:

  • 4321之后是1234,所以保证之后部分递,找到转折点index,转折数index - 1

  • 找到转折点之后的最后一个比转折数的数,交换它们

  • 对index到最后递减的子数组进行反转

121543321 --> 122543311 --> 122113345

Code

Last updated