Lintcode 388. Permutation Sequence (Medium) (Python)

第K个排列序列
本文介绍了一种算法,用于找出所有可能的排列中第K个排列的解决方案。该算法使用了阶乘和数组来帮助计算并返回指定位置的排列。

Permutation Sequence

Description:

Given n and k, return the k-th permutation sequence.

Example
For n = 3, all permutations are listed as follows:

“123”
“132”
“213”
“231”
“312”
“321”
If k = 4, the fourth permutation is “231”

Challenge
O(n*k) in time complexity is easy, can you do it in O(n^2) or less?

Notice
n will be between 1 and 9 inclusive.

Code:

class Solution:
    """
    @param n: n
    @param k: the k th permutation
    @return: return the k-th permutation
    """
    def getPermutation(self, n, k):
        # write your code here
        res = ''
        k -= 1
        fac = 1
        for i in range(1, n): fac *= i
        num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        for i in range(n-1, -1, -1):
            cur = num[int(k/fac)]
            res += str(cur)
            num.remove(cur)
            k %= fac
            if i!=0: fac /= i
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值