小编d_d*_*ric的帖子

该硬币找零算法的时间复杂度是多少?

我在leetcode上解决了硬币兑换问题https://leetcode.com/problems/coin-change-2/

这是我写的代码:

    def change(self, amount: int, coins: List[int]) -> int:
        def helper(amount, coins, ind):
            if amount == 0:
                return 1
            if amount < 0:
                return 0
            if (amount, ind) in dp:
                return dp[(amount, ind)]

            res = 0
            for i in range(ind, len(coins)):
                res  += helper(amount - coins[i], coins, i)

            dp[(amount, ind)] = res
            return res

        coins.sort()
        dp = {}
        return helper(amount, coins, 0)
Run Code Online (Sandbox Code Playgroud)

我注意到我在分析记忆算法的时间复杂度方面遇到了很多困难。例如,在这种情况下,我认为我们有amount * number of coins子问题 - >因此算法O(amount * number of coins * …

algorithm recursion memoization time-complexity coin-change

5
推荐指数
1
解决办法
866
查看次数

如何在 python3 中将负位表示的数字转换为其实际的负 int 值?

你好,我已经解决了这个 leetcode 问题https://leetcode.com/problems/single-number-ii。目标是在 O(n) 时间和 0(1) 空间内解决问题。我写的代码如下:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        counter = [0 for i in range(32)]
        result = 0
        for i in range(32):
            for num in nums:
                if ((num >> i) & 1):
                    counter[i] += 1
            result = result | ((counter[i] % 3) << i)
        return self.convert(result)
        #return result

    def convert(self,x):
        if x >= 2**31:
            x = (~x & 0xffffffff) + 1
            x = -x
        return x
Run Code Online (Sandbox Code Playgroud)

现在有趣的部分是在convert函数中,因为Python使用对象来存储int而不是32位字或其他东西,所以当my的MSB …

python algorithm bit-manipulation bit python-3.x

2
推荐指数
1
解决办法
1339
查看次数