class Solution {
public:
string getPermutation(int n, int k) {
string res;
int divider[10];//save 1! 2! ... (n-1)!
bool visited[10]={0};//mark the numbers are already used
divider[1]=1;
for(int i=2;i<=n;i++)
divider[i]=divider[i-1]*i;
k--;//this is for the calculation of every number
for(int i=1;i<=n;i++)
{
int count=k/divider[n-i]+1;
int j;
for(j=1;j<=n;j++)
{
if(!visited[j])
count--;
if(!count)
break;
}
visited[j]=1;
res+=j+'0';
k%=divider[n-i];
}
return res;
}
};
leetcode 60: Permutation Sequence
最新推荐文章于 2020-06-01 17:59:09 发布