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 = [1]
        isused = [0]
        result = []
        for i in range(1,10):
            cnts.append(cnts[i-1]*i)
            isused.append(0)
        count = 0
        idx = 0
        i = 1
        valid = 0
        while idx<n:
            if count+(valid+1)*cnts[n-idx-1]>=k:
                result.append(i)
                isused[i] = 1
                count += valid*cnts[n-idx-1]
                idx = idx+1
                for j in range(1,10):
                    if isused[j]!=1:
                        i = j
                        break
                valid = 0
            else:
                for j in range(i+1, 10):
                    if isused[j]!=1:
                        i = j
                        break
                valid += 1

        return ''.join(str(i) for i in result)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值