1 class Solution: 2 def groupSize(self,k):#计算阶乘 3 gSize = 1 4 while k != 0: 5 gSize *= k 6 k -= 1 7 return gSize 8 9 def getUnlockNum(self,nums,idx): 10 pos = 0 11 for i in range(len(nums)): 12 if nums[i] == 0: 13 pos += 1 14 if== POS IDX: 15 the nums [I] = . 1 16 return STR (I + . 1 ) . 17 18 is DEF getPermutation (Self, n-: int , K: int ) -> : STR . 19 COUNT = 0 the length of the record string concatenation # 20 is Bloks = [ 0 ] * n-recording locked state # 21 is RES = '' 22 is for I in Range (n-): 23 is gSize self.groupSize = (n--Count - . 1 ) each number # 24 Groups = N-divided into groups of count # 25 IF Groups == . 1 : 26 is RES = + self.getUnlockNum (Bloks, . 1 ) 27 the else : 28 S = K // gSize 29 P = K% gSize 30 Fixed = 0 31 is IF P> 0 : 32 Fixed + = 1 33 is GroupNum = S + Fixed # of groups (numbered from 1) 34 is RES = + self.getUnlockNum (Bloks, GroupNum) 35 IF= P! 0 : 36 k = P # update value k calculated by the remainder of this 37 [ the else : 38 is k = gSize 39 COUNT = + . 1 length recording of res # 40 return res
Process analysis, to (4,9), for example:
4 * 3 * 2 * 1 = 24
The first digit of the selection
by the 1 * 2 * 3 = 6 for a group of 24, then divided into 4 groups
1-6 of the first group of
7-12 second set
13-18 of the third group
19-24 IV group
dividend is 9, 6 divisor
9 @ 6 = 1
9% 3 6 => 0
Thus 9 of the second group
in 1234, the traversal from left to right, to find the second number 2 is not locked, and lock, returns this number
array state to 1 [2] 34
The second digit selected
by 2 * 1 = 2 is set, a total of six, are divided into three groups
1-2 of the first group
3-4 second group
5-6 third set of
remainder of the dividend prior to 3, 2 is a divisor of
each number, if the remainder is 0, the dividend is equal to the previous
3 // 2 = 1
3% 2 = 1> 0
Therefore 3 of the second group
in the 1 [2] 34, the traverse from left to right , find the two numbers 3 unlocked, locked and returns this number
array state to a [2] [3] 4
Third digit selected
by 1 = 1 is set, a total of two, then divided into two groups
one of the first group
2 of the second group of
the remainder of the dividend prior to a divisor is 1
if the remainder is 0, the dividend is equal to the previous the number of each group
1 // 1 = 1
1 = 0% 1 == 0
therefore the group 1 1
1 [2] [3] 4, traversing from left to right, the first one found unlocked digital 1, and lock it, returns this number
status array becomes [1] [2] [3] 4
The fourth digit selection
because only unlocked digital one, thus directly returns this number to obtain a final result