# 31. Next Permutation 下一个排列

@TOC

## # 题目描述

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　　7　　4　　3　　1

1　　3　　1　　2　　4　　7

``````class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
i = n - 1
while i > 0 and nums[i] <= nums[i - 1]:
i -= 1
self.reverse(nums, i, n - 1)
if i > 0:
for j in range(i, n):
if nums[j] > nums[i-1]:
self.swap(nums, i-1, j)
break

def reverse(self, nums, i, j):
"""
contains i and j.
"""
for k in range(i, (i + j) / 2 + 1):
self.swap(nums, k, i + j - k)

def swap(self, nums, i, j):
"""
contains i and j.
"""
nums[i], nums[j] = nums[j], nums[i]
``````

C++代码如下：

``````class Solution {
public:
void nextPermutation(vector<int>& nums) {
const int N = nums.size();
int i = N - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) --i;
int j = N - 1;
if (i >= 0) {
while (nums[j] <= nums[i]) --j;
swap(nums[i], nums[j]);
}
reverse(nums.begin() + i + 1, nums.end());
}
};
``````

### # 库函数

``````class Solution {
public:
void nextPermutation(vector<int>& nums) {
next_permutation(nums.begin(), nums.end());
}
};
``````

1. https://leetcode.com/articles/next-permutation/
2. https://blog.csdn.net/tstsugeg/article/details/50261517
3. http://www.cnblogs.com/grandyang/p/4428207.html

## # 日期

2018 年 8 月 27 日 ———— 就要开学了！ 2019 年 1 月 14 日 —— 凛冬将至