题目:
给定不同面额的硬币 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