Permutation Sequence
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.
class Solution {
public:
string getPermutation(int n, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n==1)
return "1";
vector<int> fac;
vector<int> pos;
string s;
fac.push_back(1);
s+='1';
for(int i=2;i<n;++i){
fac.push_back(fac.back());
fac.back()*=i;
s+=i+'0';
}
s+=n+'0';
--k;
for(int i=fac.size()-1;i>=0;--i){
pos.push_back(k/fac[i]);
k=k%fac[i];
}
for(int i=0;i<pos.size();++i){
if(pos[i]==0)
continue;
int next=pos[i];
int tmp=s[i];
s[i]=s[i+next];
while(next>1){
s[i+next]=s[i+next-1];
--next;
}
s[i+1]=tmp;
}
return s;
}
};