题目
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.
输出从1~n的n个数组成的排列中第K小的。
注意到第i位(从1开始计数)的数字增加1,排列序号增加(n-1)!,可以由此从高位开始依次确定每位的数字。
每次已经被选的数字需要在低位的筛选过程中剔除。
代码:
class Solution {
public:
string getPermutation(int n, int k) {
string ans;
if(n<=0)
return ans;
int num[9]={1},flag[9]={0}; //第i位(从0开始)后面i个数字的排列数,数字i+1是否已经取过
num[1]=1;
int i,j,id,count;
for(i=1;i<9;i++) //获取第i位(从0开始)后面i个数字的排列数的查找表
num[i]=num[i-1]*i;
for(i=n-1;i>=0;i--) //从头开始确定每位的数字
{
id=(k-1)/num[i]+1; //确定该位是没取数字中的从小开始的第几个数字
count=0;
for(j=0;j<n;j++) //寻找该数字
{
if(flag[j]==0)
{
count++;
if(count==id)
{
ans.push_back('1'+j);
flag[j]=1;
break;
}
}
}
k-=(id-1)*num[i]; //修改序号,适应下一位
}
return ans;
}
};