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.
// 3 ms
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int multical(int n) //阶乘函数
{
if(n <= 1)
return 1;
return n*multical(n-1);
}
string getPermutation(int n, int k) //n 位数字
{
string res;
int Index[10] = {};
vector<char> Table;
for(int i=1;i<=n;i++) //初始化
Table.push_back(i+'0');
for(int i=0;i<n;i++) //当前位的字符串,在Table中的位置
{
Index[i] = max(0,(k-1)/multical(n-i-1)); //不能为负数
k -= (Index[i]*multical(n-i-1));
}
for(int i=0;i<n;i++)
{
res += Table[Index[i]];
vector<char>::iterator it;
for(it=Table.begin();it!=Table.end();it++)
{
if(*it == Table[Index[i]])
{
Table.erase(it);
break;
}
}
}
return res;
}
int main()
{
int n, k;
while(cin>>n>>k)
{
cout<<getPermutation(n, k)<<endl;
}
return 0;
}
照惯例贴上solution区简短的代码
string getPermutation(int n, int k) {
int i,j,f=1;
// left part of s is partially formed permutation, right part is the leftover chars.
string s(n,'0');
for(i=1;i<=n;i++){
f*=i;
s[i-1]+=i; // make s become 1234...n
}
for(i=0,k--;i<n;i++){
f/=n-i;
j=i+k/f; // calculate index of char to put at s[i]
char c=s[j];
// remove c by shifting to cover up (adjust the right part).
for(;j>i;j--)
s[j]=s[j-1];
k%=f;
s[i]=c;
}
return s;
}