[A]配列LeetCode 31

トピックリンク

[説明]


右から最初のドロップの位置を見つけるために左にI(すなわち満たすNUMS [I] <NUMS [I + 1]);
次いで、[I + 1..len-1]が見出され、この間隔内の最大添字のk 、そうNUMS [K]> NUMSそのIが
(I + 1..len-1)の性質注意この段落が単調減少している
とスワップ(NUMS [K]、NUMS [I]);
て、[I + 1 ..len-1]、それをひっくり返すのこのストレッチ。
あなたはnext_permutationを得ることができます

[コード]

class Solution {
public:
    void swap(int &a,int &b){
        int t = a;a = b;b = t;
    }

    void _reverse(vector<int>&nums,int l,int r){
        while(l<=r){
            swap(nums[l],nums[r]);
            l++;r--;
        }
    }

    void nextPermutation(vector<int>& nums) {
        int len = nums.size();
        int j = -1;
        for (int i = len-1;i >= 0;i--){
            if (i-1>=0 && nums[i]>nums[i-1]){
                j = i-1;
                break;
            }
        }
        if (j==-1){
            _reverse(nums,0,len-1);   
        }else{
            for (int i = len-1;i >= 0;i--){
                if (nums[i]>nums[j]){
                    swap(nums[i],nums[j]);
                    break;
                }
            }
            _reverse(nums,j+1,len-1);
        }
    }
};

おすすめ

転載: www.cnblogs.com/AWCXV/p/11839690.html