# [leetcode]Permutation Sequence @ Python

The set [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):

1. "123"
2. "132"
3. "213"
4. "231"
5. "312"
6. "321"

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

5! * 5 + 1 = 601 > k，所以第一位不可能是6.

class Solution:
# @return a string
# def dfs(self, n, k, string, stringlist):
#     if len(stringlist) == n:
#         Solution.count += 1
#         if Solution.count == k:
#             print stringlist
#             return
#     for i in range(len(string)):
#         self.dfs(n, k, string[:i]+string[i+1:], stringlist+string[i])

# def getPermutation(self, n, k):
#     string = ''
#     for i in range(n): string += str(i+1)
#     Solution.count = 0
#     self.dfs(n, k, string, '')
def getPermutation(self, n, k):
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 reversed(range(n)):
curr = num[k/fac]
res += str(curr)
num.remove(curr)
if i !=0:
k %= fac
fac /= i
return res

posted @ 2014-06-13 11:48  南郭子綦  阅读(4570)  评论(0编辑  收藏  举报