[LeetCode]题解(python):060-Permutation Sequence
题目来源
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)
1 class Solution(object): 2 def getPermutation(self, n, k): 3 """ 4 :type n: int 5 :type k: int 6 :rtype: str 7 """ 8 res = "" 9 10 nums = [i + 1 for i in xrange(n)] 11 #count from 0 12 k -= 1 13 fac = 1 14 for i in xrange(1, n): 15 fac *= i 16 for i in reversed(xrange(n)): 17 index = k / fac 18 value = nums[index] 19 res += str(value) 20 nums.remove(value) 21 if i != 0: 22 k %= fac 23 fac /= i 24 return res