Leetcode 60. Permutation Sequenc

2017-06-22  本文已影响0人  persistent100

题目

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;
}
上一篇 下一篇

猜你喜欢

热点阅读