# leetcode-31 下一个排列

Eng version:

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

1. Find the largest index k such that nums[k] < nums[k + 1]. If no such index exists, the permutation is sorted in descending order, just reverse it to ascending order and we are done. For example, the next permutation of [3, 2, 1] is [1, 2, 3].
2. Find the largest index l greater than k such that nums[k] < nums[l].
3. Swap the value of nums[k] with that of nums[l].
4. Reverse the sequence from nums[k + 1] up to and including the final element nums[nums.size() - 1].

1.找到所有满足nums[k]<nums[k+1]的情形中，使k最大的那个

2.再找到所有满足nums[l]>nums[k]中,使l最大的那个

3.交换nums[k],nums[l]

4.对nums[k]之后的元素(不包括nums[k])进行反转，即可得到结果

class Solution {
public:
void nextPermutation(vector<int>&nums) {
int len = nums.size();
int k = -1, l = 0, i = 0;//注意三个变量的初始化值

for (i = len - 2/*即倒数第二个元素(逆序遍历)*/;i >= 0;--i)
if (nums[i + 1] > nums[i]) {
k = i;
break;//因为是逆序,故此时得到的k一定是最大的
}

if (k == -1) {
reverse(nums.begin(), nums.end());//此时代表原数组为逆序排列,故直接反转
return;
}

//接下来找i
for (i = len - 1;i >= 0;--i) {
if (nums[i] > nums[k]) {
l = i;
break;
}
}

//二者交换
swap(nums[k], nums[l]);

//再反转k之后的元素(不包括nums[k])
reverse(nums.begin() + k + 1, nums.end());

}
};