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).spa

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

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

 

 

next_permutation的算法步驟(二找,一交換,一翻轉):
(1)    找到排列中最右邊一個升序的首位位置i,x=nums[i]
(2)    找到排列中第i位右邊最後一個比x大的位置j,y=nums[j]
(3)    交換x,y
(4)    把第i+1位到最後的部分進行翻轉
  1. class Solution {
    private:
        void reverse(vector<int>& nums,int from,int to){
            while(from<to){
                int temp=nums[from];
                nums[from++]=nums[to];
                nums[to--]=temp;
            }
        }
    public:
        void nextPermutation(vector<int>& nums) {
            int size=nums.size();
            int i=size-2;
            while(i>-1&&nums[i]>=nums[i+1])
                i--;
            if(i<0){
                reverse(nums,0,size-1);
                return;
            }
            int k=size-1;
            while(k>i&&nums[k]<=nums[i])
                k--;
            swap(nums[i],nums[k]);
            reverse(nums,i+1,size-1);
        }
    };
相關文章
相關標籤/搜索