# LeetCode 322 Coin Change (完全背包)

988人阅读 评论(0)

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.

public class Solution {

public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for(int i = 0; i < coins.length; i ++) {
for(int j = 0; j <= amount; j ++) {
int pre = j - coins[i];
if(pre >= 0 && dp[pre] < Integer.MAX_VALUE) {
dp[j] = Math.min(dp[j], dp[pre] + 1);
}
}
}
if(dp[amount] == Integer.MAX_VALUE) {
return -1;
}
return dp[amount];
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：713815次
• 积分：15006
• 等级：
• 排名：第909名
• 原创：815篇
• 转载：7篇
• 译文：0篇
• 评论：122条
博客专栏
 LeetCode 文章：134篇 阅读：73669
 Java学习笔记 文章：10篇 阅读：10508
 算法题 文章：49篇 阅读：31907
阅读排行