Leetcode 60. Permutation Sequence

n=4,k=9
There are 4 groups of n=4 (1-6,7-12,13-18,19-24), 9 belongs to the second one. So the first number is the second one of [1,2,3,4], which is 2.
There are 3 groups of n=3 (1-2,3-4,5-6), the remainder of 9/6 is 3, belongs to the second group. So the second number is the second number of [1,3,4], which is 3.
There are 2 groups of n=2 (1,2), the remainder of 3/2 is 1, belongs to the first group. So the third number is the first one of [1,4], which is 1.

Wrong version (lose k-=1)

input: 3 3
output: “231"
expected: “213"

class Solution:
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        ans = ''
        fact = [1] * n
        num = [str(i) for i in range(1, 10)]
        for i in range(1, n):
            fact[i] = fact[i - 1] * i
        for i in range(n, 0, -1):
            first = k // fact[i - 1]
            print(k,first)
            k %= fact[i - 1]
            ans += num[first]
            num.pop(first)
        return ans
class Solution:
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        ans = ''
        fact = [1] * n
        num = [str(i) for i in range(1, 10)]
        for i in range(1, n):
            fact[i] = fact[i - 1] * i
        k -= 1
        for i in range(n, 0, -1):
            first = k // fact[i - 1]
            print(k,first)
            k %= fact[i - 1]
            ans += num[first]
            num.pop(first)
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值