天天看点

Leetcode#60. 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 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:

Input: n = 3, k = 3

Output: “213”

Example 2:

Input: n = 4, k = 9

Output: “2314”

题意

给出一个n说明一共有[1,2,…n]个可选数,然后按照字典序选出它排列组合的第k个

想法

这个当时学组合数学的时候有接触过,最简单的想法就是直接去遍历字典序然后当遍历到指定次数时停止,我没有试过,因为我觉得这样的方法还是蛮复杂,这里的复杂是说处理复杂了,有很多冗余,比如说你知道开头为1的组合种类本来就比目标下标小,但你还是直接把1开头的组合遍历了一遍,这个是没有必要的。

我的想法就是能够找出当前数字开头的话能不能覆盖到目标数,比如n=4,k=9,以1开头能覆盖到1x3!=6,不够大,换2,2x3!=12,说明就在2的区间内,那你就把2之前的组合给做一个计数,然后递归去找,k=k-1x3!=3,这时候有个注意的地方就是2就在后面的序列中不能用了,这时候重新计数,1x2!=2,小了,2用过了,换3,2x2!=4,覆盖到了,继续,k=k-1x2!=1,这时待选数字只剩下[1,4],还是从小到大找,1x1!=1,刚好,k=k-0x1!=1,最后1x0!=1,完成覆盖。这里有两个地方需要注意,一个是选过的数字不能再选,另外一个是找到一个数刚好能覆盖到目标数后,目标数k减去的是这个数的前面的数能覆盖到的区域,因为当前数覆盖的区域是可能会大于目标数,我们的想法是递归缩小范围。

参考代码

class Solution:
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        cnts = []
        isused = []
        result = []
        for i in range(,):
            cnts.append(cnts[i-]*i)
            isused.append()
        count = 
        idx = 
        i = 
        valid = 
        while idx<n:
            if count+(valid+)*cnts[n-idx-]>=k:
                result.append(i)
                isused[i] = 
                count += valid*cnts[n-idx-]
                idx = idx+
                for j in range(,):
                    if isused[j]!=:
                        i = j
                        break
                valid = 
            else:
                for j in range(i+, ):
                    if isused[j]!=:
                        i = j
                        break
                valid += 

        return ''.join(str(i) for i in result)