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 and use only constant 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
翻译
实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
必须原地修改,只允许使用额外常数空间。
以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1
分析
由于越右边对字典序影响越小,所以要找到下一排序其实就是要将尽可能右边的一个小一点的数字换成比它大一点的数字。所以我们的方法就是从倒数第二个开始向左边遍历,去找遍历的这个数右边有没有比它大的数,并且还要是最小的,最靠左边的(有点绕,不过应该还是容易理解的)。交换两个数的位置,再将被交换的较靠左的那个下标右边所有的数升序排列,即是下一个排序。
找不到的话,则只需要前后对应两两交换即可完成最小字典序。
用异或操作提高效率。
c++实现
class Solution {
public:
void nextPermutation(vector<int>& nums) {
bool find = false;
for (</