Permutation Sequence
Problem: Permutation Sequence
It's actually a math problem. For permutations of n numbers, they are grouped into n groups size of (n-1)!. Based on this property, we can get the permutation we want quickly.
Code in Python:
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
ans, nums = "", [x for x in range(1,n+1)]
for i in xrange(n-1, -1, -1):
index, k = (k-1)/math.factorial(i), k%math.factorial(i)
ans += str(nums[index])
nums.pop(index)
return ans