您的位置:首页 > 编程语言 > Python开发

[LeetCode]题解(python):060-Permutation Sequence

2015-11-23 13:49 621 查看
[b]题目来源:[/b]

  https://leetcode.com/problems/permutation-sequence/

[b]题意分析:[/b]

  输入1到9的一个数n。将[1,...,n]排列好。输出这个第k个排列。

[b]题目思路:[/b]

  不难发现,以1开头的所有排列的个数一共(n-1)!。所以当k小于(n - 1)!那么开头的数为1.根据这个规律,我们可以得到剩下的数里面第(k - 1) // (n-1)大数是第一个数。其他位数也可以根据这个规律获得。

[b]代码(python):[/b]

  

import math
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
ans, m = [],n - 1;k -= 1
visit = [False for i in range(n)]
while m > 0:
fm = math.factorial(m)
tmp = k // fm;k %= fm
i,t = 0,1
while i <= tmp:
if not visit[t - 1]:
if i == tmp:
visit[t - 1] = True;ans.append(t);break
i += 1
t += 1
m -= 1
i = 0
while visit[i]:
i += 1
ans.append(i + 1)
res = ""
for i in ans:
res += str(i)
return res


View Code

转载请注明出处:http://www.cnblogs.com/chruny/p/4988243.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: