You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.
You may assume that you have an infinite number of each kind of coin.
The answer is guaranteed to fit into a signed 32-bit integer.
示例
示例 1:
输入:amount = 5, coins = [1, 2, 5]
输出:4
解释:有四种方式可以凑成总金额:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
示例 2:
输入:amount = 3, coins = [2]
输出:0
解释:只用面额 2 的硬币不能凑成总金额 3 。
示例 3:
输入:amount = 10, coins = [10]
输出:1
解题
class Solution {
public int change(int amount, int[] coins) {
int len = coins.length; // int n = coins.length;
int[][] dp = new int[len + 1][amount + 1];
// base_case
for (int i = 0; i <= len; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= len; i++) {
for (int j = 1; j <= amount; j++) {
if (j - coins[i - 1] < 0) { // 第 i-1 个硬币面额都比 j 大,无法包含
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]];
}
}
}
return dp[len][amount];
}
}
本篇文章来源于微信公众号:程序IT圈
原创文章,作者:栈长,如若转载,请注明出处:https://www.cxyquan.com/19196.html