[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"
Note: Given n will be between 1 and 9 inclusive.
Solution:
class Solution:
# @return a string
def getPermutation(self, n, k):
numberPermutations = []
count = 1
numberPermutations.append(count)
for i in range(1, n):
count *= i
numberPermutations.append(count)
numbers = []
for i in range(1, n+1):
numbers.append(i)
solution=[]
count = k-1
for i in range(0,n):
position = count//numberPermutations[n-i-1]
count -= position * numberPermutations[n-i-1]
element = numbers.pop(position)
solution.append(str(element))
return "".join(solution)
No comments :
Post a Comment