# 【每日一题】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 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. 如果下标<0,说明这个排列应该是最后一个，返回全序列的升序排序结果；
3. 如果不为0，在这个元素之后找到第一个比它大的数字的下标，两者交换，对后续子数组做升序排序即可。

class Solution {
public:
void nextPermutation(vector<int>& nums) {
# 1,2,4,3,0
if (nums.empty()) return;
int size = nums.size(), i = size - 2, j = size - 1;

while (i>=0 && nums[i] >= nums[i+1]) i--;

if (i >= 0){
while (nums[j] <= nums[i]) j--;
swap(nums[i], nums[j]);
}
reverse(nums.begin()+i+1, nums.end());
}
};


## Reference

https://www.cnblogs.com/grandyang/p/4428207.html

01-09 11
01-03 1万+