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.
这个字符串的规律就是由小到大的数字序列,第k个字符串就是第k大的数字序列字符串,那么暴力遍历是可行的,但是太慢。
还有个方法就是康托展开,时间复杂度O(n),空间复杂度O(1)。
1 class Solution { 2 public: 3 string getPermutation(int n, int k) { 4 vector<int> numbers; 5 for(int i=1;i<=n;i++) 6 { 7 numbers.push_back(i); 8 } 9 vector<int> result; 10 int b=k-1; 11 for(int i=n-1;i>=0;i--) 12 { 13 int a=b/(jiecheng(i)); 14 result.push_back(numbers[a]); 15 numbers.erase(numbers.begin()+a); 16 if(i!=0) 17 { 18 b=b%(jiecheng(i)); 19 } 20 } 21 string result_str; 22 for(int i=0;i<result.size();i++) 23 { 24 char ch=result[i]+48; 25 result_str+=ch; 26 } 27 return result_str; 28 } 29 int jiecheng(int n) 30 { 31 int result=1; 32 for(int i=1;i<=n;i++) 33 { 34 result*=i; 35 } 36 return result; 37 } 38 };