leetcode:Next Permutation,space

來源:互聯網
上載者:User

leetcode:Next Permutation,space

一、     題目

     這道題給出一個數列,求大於這個數列的最小數列。

例如:

1,2,3 → 1,3,2

3,2,1 → 1,2,3

1,1,5 → 1,5,1

二、     分析

喜歡使用C++的童鞋或許會馬上想到next_permutation()這個庫函數,沒錯,其實這道題就是實現的它(嚴格說來只是初步實現),如果可以的話,如果直接輸入這一行代碼就可通過:

 

void nextPermutation(vector<int> &num) {       next_permutation( num.begin(), num.end() );}

但是,可不是說我們就這樣結束了,當然不能,我們要自己實現它。觀察數列會發現,如果數列是遞減的話我們是找不出比他更大的數列的,所以我們要找到兩個遞增元素,即從右至左找到第一個左邊小於右邊的元素,然後我們再找出該元素右邊比他大的最小的元素,交換兩數,然後再將該數後面的數列reverse()即可。

分為四步:

1、         從右至左找到第一個左邊小於右邊的元素num[i];

2、         從右至左找到第一個大於num[i]的元素num[j]

3、         交換num[i]和num[j];

4、         將num[i]後的數列reverse()

代碼如下:

 

class Solution {public:    void nextPermutation(vector<int> &num) {        int len = num.size()-1;        int count = len-2;        int i,j;        for(i=len-1; i>=0; i--){        if(num[i+1]>num[i]){        for(j=len; j>i-1; j--){        if(num[j]>num[i])        break;        }        swap(num[i],num[j]);        reverse(num.begin()+i+1,num.end());        return;        }        }        reverse(num.begin(),num.end());        return;    }        void swap(int &a, int &b){    a = a + b;b = a - b;a = a - b;     }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.