leetcode Permutation Sequence

題目描述:python

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 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.
Given k will be between 1 and n! inclusive.

Example 1:app

Input: n = 3, k = 3
Output: "213"

Example 2:spa

Input: n = 4, k = 9
Output: "2314"

即:對於一個整數n,共有n!個排列,給出數字k,返回第k個全排列code

觀察題目可得以下規律:blog

對於n,其中每一個字母 開頭的全排列共有n-1!個,如數字3,以 1開頭的共有2!個。遞歸

所以:m= k / (n-1)!  能夠肯定出第一個數字, 將該數字加入返回值列表中。隊列

    k %(n-1)! 能夠獲得在剩餘的數字列表中,該取第幾個 即 k = k%(n-1)!rem

所以採用循環或者遞歸可解決get

這裏注意邊界(結束)條件: 當k%(n-1)! ==0時,實際爲 以m-1開頭的最後一個排列,所以,將m-1放入隊列,剩下的數字倒序便可io

          當k%(n-1)! == 1時,即以 m開頭的第一個,將m放入隊列,其他數字依次放入便可。

代碼以下:

#!/usr/bin/python
#coding=utf-8

class Solution(object):
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
         """
        res = ''
        step = n - 1
        used = []
        use = 0
        remain = list(range(1, n+1))
        if step == 0:
            return str(n)
        while(step != 0):
            maxPer = self.factorial(step)
            firstOrder = k / maxPer
            secondOrder = k % maxPer
            if secondOrder == 0:
                use = remain.pop(firstOrder-1)
            else:
                use = remain.pop(firstOrder)
            res = res + str(use)
            used.append(use)
            if not remain:
                return res
            if secondOrder == 1:
                tmp = reduce(lambda x, y: str(x)+str(y), remain)
                res = res + str(tmp)
                return res

            if secondOrder == 0:
                if not remain:
                    return res
                tmpList = remain
                tmpList.reverse()
                tmp = reduce(lambda x, y: str(x)+str(y), tmpList)
                res = res + str(tmp)
                return res
            k = secondOrder
            step = step - 1

    def factorial(self, n):
        return reduce(lambda x,y:x*y,[1]+range(2,n+1))
s = Solution()
print s.getPermutation(3, 6)
相關文章
相關標籤/搜索