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;
    }
};

题目来源

相关文章
相关标签/搜索