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调换了没有用。

7、5和1调换了也没有效果,因此而发现了8、7、5、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;
	}
};

题目来源

原文地址:https://www.cnblogs.com/ranjiewen/p/8370961.html