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 int A[9] = {1,1, 2, 6, 24, 120, 720, 5040, 40320}; string res = ""; vector<bool> flag(n+1, false); for(int i = n-1; i >= 0; --i) { int pos = k / A[i]; if(k%A[i] ==0 && pos > 0) --pos; k = k - pos * A[i]; for(int j = 1; j <= n; ++j) { if(flag[j] == false){ if(pos == 0) { char c = '0' + j; res += c; flag[j] = true; break; }else{ --pos; } } } } return res; } };