"321"Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
Analysis:The first thought of the violence law is arranged one by one until the k Order is found. After the submission, it will time out. After searching online, we can find that we can directly construct the k arrangement, take n = 4, k = 17 as an example. The array src = [1, 2, 3 ,..., n].
What is the first number of 17th orders? We know the number of orders starting with a fixed number = (n-1 )! = 3! = 6, that is, a total of 6*2 = 12, 12 <17, so the first number of 17th orders cannot be 1 or * 3> 17, therefore, the first number of 17th orders is 3. That is, the first number of 17th arrays is the number of m = upper (17/6) = 3 (upper indicates an ascending integer) of the original array (ascending order of the original array.
After the first number is fixed, we delete the number from the src array, which is equivalent to finding the k-(m-1) * (n-1) based on the current src )! = 17-2*6 = 5 arrays, so this problem can be solved recursively.
In code implementation, pay attention to a small detail, that is, starting from k -- to make the subscript start from 0. In this way, the subscript is from 0 to n-1, so we do not need to consider n to get the remainder, better match with the array subscript. The Code is as follows:
Class Solution {public: int fun (int n) {if (n <0) return 0; else if (n = 0) return 1; elsereturn n * fun (n-1);} string getPermutation (int n, int k) {string s; int total = fun (n); if (total
Flag (n, 0); // because the array is from 0 to n-1, so the base from 0 to K-1 -- k; for (int I = 0; I