算法作业系列14
Coin Change
写在前面
争取一日一道算法题,大学也已经过了三年了,是时候正视一下自己的未来了。
题目
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:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
思路
其实看到第一反应就是,这不是背包问题吗?冥思苦想之下发现自己还是没办法记得背包问题怎么写,因此上维基查了一下,再来动手写这道题。
其实思路很简单,只要想出来状态转移方程怎么写,剩下的就是很短的代码了,那我们就要想,怎么去把这道题转成规模更小的子问题呢?其实很简单,对于每一个数值,只需要减去一个可以交换的硬币面额,再递归求解就可以啦!具体状态转移方程如下:
dp(i) = min

这篇博客介绍了Coin Change问题,即如何用最少数量的硬币找零。作者通过举例说明问题,指出这是一类背包问题,并提供了思路和状态转移方程。由于递归解决方案可能导致超时,作者建议使用动态规划优化,通过空间换时间来避免重复计算,从而提高效率。
最低0.47元/天 解锁文章
2104

被折叠的 条评论
为什么被折叠?



