Permutation Sequence
Description:
Given n and k, return the k-th permutation sequence.
Example
For n = 3, all permutations are listed as follows:
“123”
“132”
“213”
“231”
“312”
“321”
If k = 4, the fourth permutation is “231”
Challenge
O(n*k) in time complexity is easy, can you do it in O(n^2) or less?
Notice
n will be between 1 and 9 inclusive.
Code:
class Solution:
"""
@param n: n
@param k: the k th permutation
@return: return the k-th permutation
"""
def getPermutation(self, n, k):
# write your code here
res = ''
k -= 1
fac = 1
for i in range(1, n): fac *= i
num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(n-1, -1, -1):
cur = num[int(k/fac)]
res += str(cur)
num.remove(cur)
k %= fac
if i!=0: fac /= i
return res