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.


思路:很简单的背包问题,问题可以简化成规模较小的子问题,标准的动态规划。证明就不证了。

递推公式:

c[0] = 0;//初值

c[i] = MAX , i < Min(coin[j]),j∈[0,coins.length]//边界

c[i] = Math.min(c[i],c[i - coins[j]] + 1),j∈[0,coins.length]//递推公式

其中i表示装当前金额,c[i]表示装i金额所需要的最少硬币数目。

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




猜你喜欢

转载自blog.csdn.net/u013300579/article/details/80231246
今日推荐