LeetCode, leetcodeoj
Link: 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.
The requirement for this question is to return the k sequence consisting of n numbers (the n range is 1 ~ 9 ).
The labels for this question include backtracking and mathematics, but I tried to generate the k Number (k is already on n! The number of times out. I tried the next_permutation function again, but it still timed out... I don't know how to do this with tracing...
However, this is indeed a mathematical problem. Considering n different numbers, there are n in total! (N-1 )! So the first number in the k-th permutation of n numbers depends on the number (n-1) in k )!, K/(n-1 )!. And so on, the number on the I-th is the remaining k/(n-1-i )! The number on the position (the remaining k is due to k each pair (n-1-i )! Modulo ). So as long as the current k is divided by (n-1-i )!, The resulting number is the index j at the position of the remaining array. Next, retrieve the element at this position, and move the element at this position between I to another position.
In implementation, k first needs to reduce 1, because 1st has been generated, that is, to generate the K-1 on the basis of the 1st. And use f to record n !.
Time Complexity: O (n2)
Space complexity: O (n)
1 class Solution 2 { 3 public: 4 string getPermutation(int n, int k) 5 { 6 string s(n, '0'); 7 8 int i, j, f = 1; 9 for(i = 0; i < n; ++ i)10 {11 s[i] += i + 1;12 f *= i + 1;13 }14 15 for(i = 0, k = (k - 1) % f; i < n; ++ i, k %= f)16 {17 f /= n - i;18 19 int j = i + k / f;20 char c = s[j];21 while(j > i)22 s[j] = s[-- j];23 s[i] = c;24 }25 26 return s;27 }28 };
Reprinted, please describe the Source: LeetCode --- 60. Permutation Sequence