Leetcode 60. Permutation Sequence

題目

The set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.

分析

給出整數(shù)n,可以得到1-n的全排列,然后按照字典序進(jìn)行排序,輸出第k個序列。
我們可以安裝之前的方法http://www.lxweimin.com/p/85344a864cdb ,從最小的字典序,依次遞增到第k個輸出即可。但是感覺可能會比較慢。
可以換個思路思考,排序后的全排列序列是有規(guī)律的。假如n=4,第一個數(shù)字以3X2X1重復(fù)出現(xiàn),而第k個,可以看其在第幾個以6的循環(huán)中。選定后,下個數(shù)字以2X1重復(fù)出現(xiàn),而第k個在其中的k/6位置,依次往下尋找數(shù)字,直到所有數(shù)字都查找完畢。其中要注意,加入k是6的倍數(shù),則將其k=6,即在剩下的數(shù)字組成的全排序隊(duì)列中占第6個。更簡單的理解是這樣計(jì)算:k-k/6X6

char* getPermutation(int n, int k) {
    char *ans=(char*)malloc((n+1)*sizeof(char));
    int anslength=0;
    int num[n];
    int temp=1;
    for(int i=0;i<n;i++)
    {
        num[i]=i+1;
        temp=temp*(i+1);
    }
    temp=temp/n;
    
    while(k>0)
    {
        if(k>temp)
        {
            int p=0;
            if(k%temp==0)p=k/temp-1;
            else p=k/temp;
            int p1=-1;
            while(p>=0)
            {
                for(int j=p1+1;j<n;j++)
                {
                    if(num[j]!=0)
                    {
                        p1=j;
                        break;
                    }
                }
                p--;
            }
            ans[anslength]=num[p1]+'0';
            anslength++;
            num[p1]=0;
        }
        else
        {
            int p1=0;
            for(int j=p1;j<n;j++)
            {
                if(num[j]!=0)
                {
                    p1=j;
                    break;
                }
            }
            ans[anslength]=num[p1]+'0';
            anslength++;
            num[p1]=0;
        }
        printf("%s %d %d\n",ans,k,temp);
        if(k%temp!=0)
            k=k%temp;
        else
            k=temp;
        if(anslength<n)
            temp=temp/(n-anslength);
        else
            k=0;
    }
    
    ans[anslength]='\0';
    return ans;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,775評論 0 33
  • The set [1,2,3,…,n] contains a total of n! unique permuta...
    關(guān)瑋琳linSir閱讀 232評論 0 5
  • 伴隨著一場場秋雨,夏天走了,秋天慢慢的來了。 秋雨是一個很奇妙的東西,他可以讓農(nóng)民伯伯們變得開...
    史俊燁1閱讀 380評論 0 1
  • 很想,很想,很想睡到自然醒,可是睜眼一看,五點(diǎn)半,生物鐘真是強(qiáng)大。 閉眼,再睜眼,六點(diǎn)整。你閉得上眼晴,可管不住大...
    眼里的湖閱讀 601評論 2 6
  • 李老漢最近很郁悶,他收到了一張假幣,面值不大,20的。 按說20塊錢,說多也不多。李老漢拿著這張假的20塊,左看右...
    國宴閱讀 223評論 0 1