康托展开
52413 -> 4*4!+1*3!+2*2!+0*1!+0*0!=106 106+1=107
康托逆展开
1 2 3 4 5
1 1! 2! 3! 4! 5!
107 107-1=106
106 106/4!=4....10 1 2 3 4 5 -> 5
10 10/3!=1....4 1 2 3 4 -> 2
4 4/2!=2....0 1 3 4 -> 4
0 0/1!=0....0 1 3 -> 1
0 0/0!=0....0 3 -> 3
代码(c+)
class Solution {
public:
string getPermutation(int n, int k) {
string ans = "";
string nums="123456789";
vector<int> fact(1,1);
for(int i=1;i<n;i++){
fact.push_back(i*fact[i-1]);
}
k-=1;
for(int i=n;i>0;i--){
int p = k/fact[i-1];
ans +=nums[p];
nums.erase(p,1);
k = k%fact[i-1];
}
return ans;
}
};