题目:
给你一个整数数组 coins ,表示不同面额的硬币;以及一个整数 amount ,表示总金额。
计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何一种硬币组合能组成总金额,返回 -1 。
你可以认为每种硬币的数量是无限的。
示例 1:
输入:coins = [1, 2, 5], amount = 11
输出:3
解释:11 = 5 + 5 + 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/coin-change
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
动态转移方程
dp[j] = Math.min(dp[j], dp[j - coins[i]] +1);
代码:
public int coinChange(int[] coins, int amount) {
int dp[] = new int[amount+1];
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for(int i = 1; i <= amount;i++) {
for(int j = 0;j<coins.length;j++) {
if (i - coins[j] < 0 || dp[i-coins[j]] == amount + 1) {
continue;
}
dp[i] = Math.min(dp[i], dp[i-coins[j]]+1);
}
}
return dp[amount] == amount + 1 ? -1 : dp[amount];
}