題目
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的全排列,然后按照字典序進行排序,輸出第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ù)字組成的全排序隊列中占第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;
}