您的位置:首页 > 其它

Leetcode之CoinChange

2016-10-17 09:58 253 查看

题目

题目地址 https://leetcode.com/problems/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.


解题

  典型的动态规划问题,满足最优子结构和重复子问题。

  定义问题的最优解:即当零钱为amount时最少需要哪些硬币。

  最优解的值为:零钱为amount时候的最少硬币数。

  递归式求解:令f[i]为当amount为i时最少需要的硬币数,则对于某一个coin[j]满足,i>=coin[j] 则剩余的零钱数为i-coin[j],硬币数+1。递归式可写成如下:

  

f[i] = Math.min(f[i],f[i-coin[j]]+1);


定义初始值:f[0]=0。

Code

/**
* Created by bamboo on 2016/10/17.
*/
public class CoinChange {
/**
* 找出零钱为amount时候最少需要的硬币数
* @param coins
* @param amount
* @return
*/
public int coinChange(int[] coins, int amount) {
int[] f = new int[amount + 1];
f[0] = 0;
for (int i = 1; i <= amount; i++) {
f[i] = Integer.MAX_VALUE;
for (int j = 0; j < coins.length; j++) {
/*满足计算条件*/
if (i >= coins[j] && f[i - coins[j]] != Integer.MAX_VALUE) {
f[i] = Math.min(f[i], f[i - coins[j]] + 1);
}
}
}
return f[amount] == Integer.MAX_VALUE ? -1 : f[amount];
}

}


令人意外超过居然达到了80%,特此纪念

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode