1. 程式人生 > >LeetCode 31. Next Permutation

LeetCode 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 and use only constant 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

題目理解:

給定一個字元向量,對其進行操作,變成比它字典序大一個單位的新序列;如果原字典序已經是最大了,那麼就變成其最小字典序的序列。

解題思路:

因為要找上一級字典序,所以首要的是將後面大的元素提到前面去,但由於我們所求的只是上“一”級,因此,不能直接調換,具體演算法流程如下:

  1. 首先,從後向前遍歷,找到第一個比自己之前的元素大的位置,將start設定在較小元素的位置上,並記錄最小元素值。若找不到,則將原向量升序排列。
  2. 然後從較大元素的位置開始,向後遍歷,找到與剛才記錄的最小元素值相差最小的元素(為了保證只升一級),將其與最小元素進行調換。
  3. 為了真正的只升一級,還需要將更新的start位置後面的元素,按照升序排列,這樣才可以將內容值提升做到最小。

程式碼:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        //給的例子長度太小,看不出規律來,這時應該自己舉例找規律。。。
        int start = -1,end = -1;
        int base = -1;
        for(int i=nums.size()-1;i>0;i--){
            if(nums[i]>nums[i-1]){
                start = i-1;
                base = nums[i-1];
                break;
            }
        }
        if(start == -1){
            sort(nums.begin(),nums.end());
            return;
        }
        int minN = INT_MAX;
        for(int i=start+1;i<nums.size();i++){
            if(nums[i]>base){
                int tmp = nums[i] - base;
                if(tmp < minN){
                    minN = tmp;
                    end = i;
                }
            }
        }
        //exchange
        int tmp = nums[end];
        nums[end] = nums[start];
        nums[start] = tmp;
        
        //reverse the remained
        sort(nums.begin()+start+1,nums.end());
    }
};

總結:

不得不承認,如果單詞不認識的話,單看樣例是理解不了這個題的意思的,也間接告訴了自己不能偷懶不讀題,而是通過樣例去理解題意,這樣是片面的,不正確的。 我通過樣例想出的解題方法太不全面,看了solution之後立馬就明白了,是什麼意思,僅僅是因為例子變長了一些,然後通過這個變長的例子再進行思考就可以得出結論。 因此,以後做題的時候,一定要讀懂題,然後想明白題的意思與要求,再去看例子,不懂是編不出來題的!