《LeetCode笔记87》:零钱兑换

本文详细探讨了硬币兑换问题,即如何用最少数量的硬币凑足指定金额。通过示例介绍了问题背景及解决方案,使用BFS算法进行求解,并提供了Python实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。

示例 1:

输入: coins = [1, 2, 5], amount = 11
输出: 3 
解释: 11 = 5 + 5 + 1

示例 2:

输入: coins = [2], amount = 3
输出: -1

说明:
你可以认为每种硬币的数量是无限的。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/coin-change

方法一:

BFS:从一枚硬币开始,遍历1枚、2枚、3枚,.......n枚硬币能组成的值。同时利用列表记录已经出现过的值,减少时间复杂度。

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        if amount==0:
            return 0
        money = [0]
        number = [0]
        used_money = [0]*(amount+1)
        while(money):
            current_money = money.pop(0)
            current_counting = number.pop(0)
            if current_money>amount:
                continue
            for i in coins:
                if i==0:
                    continue
                if i+current_money==amount:
                    return current_counting+1
                elif i+current_money<amount and used_money[i+current_money]==0:
                    used_money[i+current_money]=1
                    money.append(i+current_money)
                    number.append(1+current_counting)
        return -1

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值