-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutationSequence.py
More file actions
29 lines (28 loc) · 852 Bytes
/
Copy pathPermutationSequence.py
File metadata and controls
29 lines (28 loc) · 852 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
# @param {integer} n
# @param {integer} k
# @return {string}
def getPermutation(self, n, k):
factorial = {}
base = 1
for i in range(1,n):
base *= i
factorial[i] = base
result = []
candidates = range(1,n+1)
while k > 1:
divisor = factorial[len(candidates) - 1]
a,k = divmod(k,divisor)
if a == len(candidates):
candidates.reverse()
break
if k == 0:
result.append(candidates[a - 1])
del candidates[a - 1]
candidates.reverse()
break
result.append(candidates[a])
del candidates[a]
result += candidates
result = [str(x) for x in result]
return "".join(result)