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.

分析

给出整数n,可以得到1-n的全排列,然后按照字典序进行排序,输出第k个序列。
我们可以安装之前的方法http://www.jianshu.com/p/85344a864cdb ,从最小的字典序,依次递增到第k个输出即可。但是感觉可能会比较慢。
可以换个思路思考,排序后的全排列序列是有规律的。假如n=4,第一个数字以3X2X1重复出现,而第k个,可以看其在第几个以6的循环中。选定后,下个数字以2X1重复出现,而第k个在其中的k/6位置,依次往下寻找数字,直到所有数字都查找完毕。其中要注意,加入k是6的倍数,则将其k=6,即在剩下的数字组成的全排序队列中占第6个。更简单的理解是这样计算: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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,767评论 0 33
  • The set [1,2,3,…,n] contains a total of n! unique permuta...
    关玮琳linSir阅读 230评论 0 5
  • 伴随着一场场秋雨,夏天走了,秋天慢慢的来了。 秋雨是一个很奇妙的东西,他可以让农民伯伯们变得开...
    史俊烨1阅读 379评论 0 1
  • 很想,很想,很想睡到自然醒,可是睁眼一看,五点半,生物钟真是强大。 闭眼,再睁眼,六点整。你闭得上眼晴,可管不住大...
    眼里的湖阅读 592评论 2 6
  • 李老汉最近很郁闷,他收到了一张假币,面值不大,20的。 按说20块钱,说多也不多。李老汉拿着这张假的20块,左看右...
    国宴阅读 214评论 0 1