LeetCode 322 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.

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];
}
}

动态规划之01背包问题及leetcode实例

2018-01-24 15:07:37

LeetCode BackPack 背包问题

2017-10-03 22:36:03

Leetcode常用五大算法思想

2015-04-20 20:57:29

背包问题总结篇

2016-05-24 14:59:53

LeetCode总结

2014-01-04 20:19:03

leetcode 279. Perfect Squares 类似背包问题 + 很简单的动态规划DP解决

2017-09-27 22:00:13

leetcode 322. Coin Change-硬币交换|动态规划

2016-03-24 23:19:37

[leetcode] 322. Coin Change

2015-12-28 11:33:16

[LeetCode 322] Coin Change

2016-01-12 16:22:11

leetcode 322. Coin Change

2016-01-22 17:25:52

不良信息举报

LeetCode 322 Coin Change (完全背包)