题目来源
https://leetcode.com/problems/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.
题意分析
Input: n, k
Output: the kth permutation in permutations based on n
Conditions: 返回第n个排列
题目思路
看了网上答案发现还有这样一个方法,每一位都是nums[k/factorial],注意k要从0计数所以要减一,nums要及时移除已使用过的元素(不移除可以用False or True数组标记),factorial一般是n-1的阶乘,以上三个数都要更新
AC代码(Python)
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
res = "" nums = [i + 1 for i in xrange(n)]
#count from 0
k -= 1
fac = 1
for i in xrange(1, n):
fac *= i
for i in reversed(xrange(n)):
index = k / fac
value = nums[index]
res += str(value)
nums.remove(value)
if i != 0:
k %= fac
fac /= i
return res