1. 程式人生 > >#Leetcode# 31. Next Permutation

#Leetcode# 31. Next Permutation

https://leetcode.com/problems/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

程式碼:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size();
        int temp1, temp2;
        for(int i = n - 2; i >= 0; i --) {
            if(nums[i + 1] > nums[i]) {
                temp1 = i;
                for(int j = n - 1; j > temp1; j --) {
                    if(nums[j] > nums[i]) {
                        temp2 = j;
                        break;
                    }
                }
                swap(nums[temp1], nums[temp2]);
                reverse(nums.begin() + i + 1, nums.end());
                return ;
            }
        }
        reverse(nums.begin(), nums.end());
    }
};

 從後向前找到第一個後面數字比前面小的位置 然後確定這個位置 再從後向前找出第一個比該數字大的位置 然後交換著兩個數字 然後這兩個數字之後對應的部分也要逆序 用到 $reverse$ 函式進行反轉  做法  get!!!