题目
给定不同面额的硬币和一个总金额。写出函数来计算可以凑成总金额的硬币组合数。假设每一种面额的硬币有无限个。
链接:https://leetcode.com/problems/coin-change-2/
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
Example:
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
思路及代码
DP
- dp[i]:总数为i时的方法总数
- dp[i] = sum(dp[i-coin]),其中i-coin>=0
- 用两层循环:假设只有1个硬币时,方法数;每次增加一个硬币,求方法数
- 初始值dp[0] = 1
<