Coin Change

来源:互联网 发布:js url动态传参数 编辑:程序博客网 时间:2024/05/16 18:31

ou 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.


比较基础的动规题,然而还是提交了三次才改过来。对于这类问题,一般是用一额嵌套的循环。对于这道题,要求的是最小的硬币数,所以amount变量应该放到外层。如果问的是有几种取法,那么需要把coins放在外层(?遇到类似题会更新这篇文章)。

这道题的转移方程是dp[j] = min( dp [j - coins[i]] +1)  if j-coins[i] >=0 and dp[j-coins[i]] != MAX_VALUE。

对转移方程的理解是,对于当前的金额,它可以通过一个子规模的最小找零数+1得到,所以最终得到的结果也是最优的。


代码:

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




0 0
原创粉丝点击