Original title address: https://oj.leetcode.com/submissions/detail/5341904/
Test instructions
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 would be between 1 and 9 inclusive.
Problem-solving ideas: Just started with DFS, but has been tle. It seems that Python is really slow to write Dfs in Java and C + +. Can only adopt a more ingenious way of thinking.
In fact, the data is not big, n up to 9,9! = 362880, the enumeration should be able to pass (I did not experiment).
The method I used was to calculate the K-permutation.
Suppose n = 6,k = 400
The first digit is calculated first,
The first bit is 6, so it's also the 5th at least! * 5 + 1 permutations, this is because when the first bit is 1/2/3/4/5, there are 5! permutations, so the first bit is 6 o'clock, at least the 5th! * 5 + 1 permutations (this arrangement is 612345).
5! * 5 + 1 = 601 > K, so the first bit cannot be 6.
Enumerate one by one until the first bit is 4 o'clock, at which point 4xxxxx is at least 5th! * 3 + 1 = 361 permutations.
Then the second digit is calculated,
The difference with the first digit is that the 46xxxx is at least 4th! * 4 + 1 = 97 permutations, this is because the smaller than 6 is only 5/3/2/1.
Finally, we can calculate the second bit as 2.
Finally, the No. 400 arrangement was 425361.
Code:
classSolution:#@return A string defgetpermutation (self, n, k):#http://www.cnblogs.com/zuoyuan/p/3785530.htmlres ="'FAC= 1k-= 1 forIinchRange (1,n): FAC *=I num= [I forIinchRange (1,10)] forIinchReversed (range (n)): Curr= num[k/FAC] Res+=Str (curr) num.remove (curr)ifI! =0:k%=FAC FAC/=IreturnRes
Reference:
Http://www.cnblogs.com/zuoyuan/p/3785530.html
[Leetcode] Permutation sequnce