天天看點

Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

<code>1,2,3</code> → <code>1,3,2</code>

<code>3,2,1</code> → <code>1,2,3</code>

<code>1,1,5</code> → <code>1,5,1</code>

思路:從後向前找,找到第一個不是逆序的位置,也就是找到一個數,它大于它後面的那個數。然後将它後面的那個數開始到數組結尾的逆序都變為正序,并且從中找出第一個大于找到的那個數并交換二者的位置。

C++代碼實作:

運作結果:

Next Permutation

繼續閱讀