[LeetCode] #31 Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.spa

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).code

The replacement must be in-place, do not allocate extra memory.blog

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排序

本題是給了左邊的一個排列,給出它的下一個排列。下一個排列是指按詞典序的下一個排列。降序的排列已是按詞典序的最大的排列了,因此它的下一個就按升序排列。it

1.從後往前,找到第一個 A[i-1] < A[i]的。
2.從 A[i]到A[n-1]中找到一個比A[i-1]大的最小值(也就是說在A[i]到A[n-1]的值中找到比A[i-1]大的集合中的最小的一個值)
3.交換這兩個值(A[i]和找到的值),而且把A[i]到A[n-1]進行排序,從小到大。
時間:16ms,代碼以下:
class Solution {
public:
    void nextPermutation(vector<int> &num) {
        int end = num.size() - 1;
        int povit = end;
        while (povit){
            if (num[povit] > num[povit-1]) 
                break;
            povit--;
        }
        if (povit > 0){
            povit--;
            int large = end;
            while (num[large] <= num[povit]) large--;
            swap(num[large], num[povit]);
            reverse(num.begin() + povit + 1, num.end());
        }
        else
            reverse(num.begin(), num.end());
    }
};
相關文章
相關標籤/搜索