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

题目来源:

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


题意分析:

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


题目思路:

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


代码(python):

  

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

原文地址:https://www.cnblogs.com/chruny/p/4988243.html