[LeeCode] 322. Coin Change (Python)

322. Coin Change

Medium

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

Example 1:

Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Note:
You may assume that you have an infinite number of each kind of coin.

 

方法1: 动态规划

dp[i]为当钱数为i时,所需要的最小硬币数

dp[i]=min(dp[i], dp[i-coin]+1)

这里为什么还要跟dp[i]比较?是因为我们在计算dp[i]的时候,需要尝试不同的硬币,所以需要比较。

dp[0]=0当没有钱的时候,我们也就不需要硬币,硬币数就变成了0。

我们设置初始的dp值为amout+1是因为当出现满足不了的情况的时候,最后dp的值会大于amount

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [amount + 1] * (amount + 1)
        dp[0] = 0
        for i in range(1, amount + 1):
            for coin in coins:
                if coin <= i:
                    dp[i] = min(dp[i], dp[i-coin] + 1)
        if dp[amount] > amount:
            return -1
        return dp[amount]

方法2:暴力搜索的优化

参考 https://www.cnblogs.com/grandyang/p/5138186.html#3974321

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        res = float('inf')
        coins.sort()
        def helper(target, start, cur):
            # 当coin的取值超过范围后,返回
            if start < 0:
                return
            nonlocal res
            # 因为我们总是从最大的硬币开始选的,所以当最大值的硬币满足的时候,也就意味着我们用了最少的硬币个数满足要求
            # 此时,得到的结果一定是最优的
            if target % coins[start] == 0:
                res = min(res, cur + target / coins[start])
                return
            # 这里我们从最大值的硬币开始选的,从最大值硬币的可用个数由多到少选择,也可能是0个
            # 比如coins=[1,2,5],target=11,我们最多只能选两个5,但是最后结果也能0个5
            for i in range(target // coins[start], -1, -1):
                if cur + i >= res - 1:
                    break
                helper(target - i * coins[start], start - 1, cur + i)
        helper(amount, len(coins) - 1, 0)
        return int(res) if res != float('inf') else -1

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值