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, 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

分析

尋找當前排列的下一個排列,即所有排列看做數字,下一個排列的值是第一個比當前排列值大的排列,具體算法參考:A simple algorithm from Wikipedia with C++ implementation (can be used in Permutations and Permutations II)

注:可以用sort代替reverse做翻轉。

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int k=-1;
        int size=nums.size();
        for(int i=0;i<size-1;++i){//先順序查找最大的下標k使得nums[k]<nums[k+1]
            if(nums[i]<nums[i+1])
                k=i;
        }
        if(k==-1){//如果沒有則整體翻轉
            sort(nums.begin(),nums.end());
            return ;
        }
        int j=-1;
        for(int i=size-1;i>k;--i){//找到k之後的最大下標使得nums[k]<nums[j]
            if(nums[k]<nums[i]){
                j=i;
                break;
            }
        }
        swap(nums[k],nums[j]);//交換後翻轉k+1到end的部分
        sort(nums.begin()+k+1,nums.end());
        
    }
};


發佈了180 篇原創文章 · 獲贊 15 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章