31. Next Permutation

歡迎fork and star:Nowcoder-Repository-github

31. 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.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

解析

  • 瞭解了全排序以後,其實就是交換數據,好比說須要交換第i和第j個元素(假設i<j),則交換完以後,第i+1及其以後的元素要進行重排序,使其遞增;那麼如今的問題就是找到要交換的元素,我所作就是從後往前查找

網上看來一個示例,以爲挺好的,也不必另外找一個了。

6 5 4 8 7 5 1

一開始沒看對方的後面介紹,就本身在想這個排列的下一個排列是怎樣的。

首先確定從後面開始看,1和5調換了沒有用。

七、5和1調換了也沒有效果,所以而發現了八、七、五、1是遞減的。

若是想要找到下一個排列,找到遞增的位置是關鍵。

由於在這裏纔可使其增加得更大。

因而找到了4,顯而易見4過了是5而不是8或者7更不是1。

所以就須要找出比4大但在這些大數裏面最小的值,並將其二者調換。

那麼整個排列就成了:6 5 5 8 7 4 1

然而最後一步將後面的8 7 4 1作一個遞增。
  • 先從後往前找到一個遞減的數位置4,而後從後找到恰好大於這個數的位置5,交換兩個數字;而後後面的數遞增排序!
// 31. Next Permutation
class Solution_31 {
public:
    void nextPermutation(vector<int> &num) {

        next_permutation(num.begin(), num.end());

        return;
    }
};

題目來源

相關文章
相關標籤/搜索