排列

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

【解法】
step1:從它的最后一個元素開始,向從后向前遍歷,找到第一個滿足nums[index] < nums[index+1]的索引index。因此,從nums[index+1, n-1]的元素是反向排序的。
(例如原始號碼135421,nums[index] = 3,nums[index+1, n-1] 值為5421,是反向排序。)

step2:為了找到下一個排列,我們必須增大nums[index]的值,同時為了使增加的量最小化,將它與num[index+1, n-1]之間的大于nums[index]的最小值交換。
(nums[index] = 3,nums[index+1, n-1]之間的大于nums[index]的最小值是4,所以交換這兩個數(shù)字,變?yōu)?45321。)

step3:最后一步是使num[index+1, n-1]盡可能小,我們只需要逆向排序num[index+1, n-1]。
(num[index+1, n-1]為5321,對其進行逆向排序,為1235,所以最終結果為141235。)

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if(nums.size()<=1)
            return;
        int index;
        for(index=nums.size()-2; index>=0; --index){
            if(nums[index]<nums[index+1])
                break;
        }
        // 當輸入為321時,index此時為-1
        if(index>=0){
            int i = nums.size()-1;
            while(nums[i]<=nums[index])
                --i;
            swap(nums[index], nums[i]);            
        } 
        reverse(nums.begin()+index+1, nums.end());
    }
};
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容