# 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

# Solution

Approach 1: One pass.

  1. Find the last descending sequence s.
  2. For the number x right before s, find the smallest number y from s such that y > x.
  3. Swap x and y.
  4. Now s is still descending. Reverse s.

# Code (Python)

Approach 1:

# Code (C++)

Approach 1:

// One pass.
// 1. Find the last descending sequence s.
// 2. For the number x right before s, find the smallest number y from s such that y > x.
// 3. Swap x and y.
// 4. Now s is still descending. Reverse s.
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int i = nums.size() - 1;
        while (i > 0 && nums[i] <= nums[i-1])
            i--;
        if (i > 0)
        {
            for (int j = nums.size() - 1; j >= i; --j)
            {
                if (nums[j] > nums[i-1])
                {
                    std::swap(nums[j], nums[i-1]);
                    break;
                }
            }
        }
        std::reverse(nums.begin() + i, nums.end());
    }
};