Permutation Sequence
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):
"123""132""213""231""312""321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
分析:使用康托展开,直接生成第k个排列。了解原理请看:康托展开。
代码:
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
remains = k - 1
div = []
for i in range(n):
a, remains = divmod(remains, self.getFactory(n - i - 1))
div.append(a)
res = ''
seq = range(1, n + 1)
for i in div:
res += str(seq[i])
del seq[i]
return res
def getFactory(self, n):
if n in [0, 1]:
return 1
return reduce(lambda x, y: x*y, range(1, n + 1))

本文介绍了一种利用康托展开直接生成特定排列的方法。针对输入整数n和k,该算法能快速找出由1到n构成的所有排列中的第k个序列。通过深入解析这一高效算法,读者可以掌握如何避免穷举所有可能排列,从而显著提高解决此类问题的效率。
5458

被折叠的 条评论
为什么被折叠?



