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.
我们以n = 4,k = 17为例,数组src = [1,2,3,...,n]。 第17个排列的第一个数是什么呢:我们知道以某个数固定开头的排列个数 = (n-1)! = 3! = 6, 即以1和2开头的排列总共6*2 = 12个,12 < 17, 因此第17个排列的第一个数不可能是1或者2,6*3 > 17, 因此第17个排列的第一个数是3。到第2位时,以某个数固定开头的排列个数即为(n-2)!,即以1和2和3的排列共2!*3=6,12+6>17,因此只能选到2,2!*2=4,12+4<17,因此第三位即为1,以此类推,得到答案,代码如下:
1 #include<iostream> 2 #include<vector> 3 #include<string> 4 using namespace std; 5 int factorial(int num) 6 { 7 int value = 1; 8 for(int j = 2;j <= num;j++) 9 { 10 value *= j; 11 } 12 return value; 13 } 14 string permutationSequence(int n,int k) 15 { 16 string str = "123456789"; 17 string getStr = str.substr(0,n); 18 string res(n,' '); 19 20 for(int i = 0;i < n;i++) 21 { 22 int temp = factorial(n-1-i); 23 int index = (k-1)/temp; 24 res[i] = getStr[index]; 25 26 getStr.erase(index,1); 27 k-=index*temp; 28 29 } 30 31 return res; 32 } 33 34 int main() 35 { 36 37 string result; 38 result = permutationSequence(4,15); 39 cout << "The result is:" << result << "\n"; 40 }