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.

解题思路;

这种题第一想法是贪心,但是事实上贪心是不可行的。例如[1,5,7],10这个例子,用贪心就是1,1,1,7,需要4个硬币,但是事实上只需要5,5即可。

//下面是错误的贪心算法
public int coinChange(int[] coins, int amount) {
	if(coins.length==0)
		return -1;
	Arrays.sort(coins);
    return countCoinChange(coins, coins.length-1, amount);
}

public int countCoinChange(int[] coins,int index,int amount){
	if(amount==0)
		return 0;
	if(index<0)
		return -1;
	int n=amount/coins[index];
	for(int i=n;i>=0;i--){
		if(countCoinChange(coins, index-1, amount-coins[index]*i)>-1)
			return countCoinChange(coins, index-1, amount-coins[index]*i)+i;
	}
	return -1;
}

然后稍加修改使用回溯算法,但是超时了,算法如下:

public int coinChange(int[] coins, int amount) {
    if(coins.length==0)
        return -1;
    Arrays.sort(coins);
    return countCoinChange(coins, coins.length-1, amount);
}

public int countCoinChange(int[] coins,int index,int amount){
    int min=Integer.MAX_VALUE;
    if(amount==0)
        return 0;
    if(index<0)
        return -1;
    int n=amount/coins[index];
    for(int i=n;i>=0;i--){
        int num=countCoinChange(coins, index-1, amount-coins[index]*i);
        if(num>=0){
            min=num+i<min?num+i:min;
        }
    }
    return min==Integer.MAX_VALUE?-1:min;
}
这种算法重复计算太多次,应该用dp算法来保存
public int coinChange(int[] coins, int amount) {
    if (coins == null || coins.length == 0 || amount <= 0) {
        return 0;
    }
    int[] min = new int[amount + 1];
    Arrays.fill(min, Integer.MAX_VALUE);
    min[0] = 0;
    helper(amount, coins, min);
    return min[amount];
}


public void helper(int amount, int[] coins, int[] min) {
    if (amount == 0) {
        return;
    }
    /*
    test if min[amount] has alreay been explored
    min[i] = -1: explored, but no combination for it. 
    min[i] = Integer.MAX_VALUE: not explored.
    */
    if (min[amount] != Integer.MAX_VALUE) {
        return;
    }
    int min_count = Integer.MAX_VALUE;
    for (int coin : coins) {
        if (amount - coin >= 0) {
            helper(amount - coin, coins, min);
            if (min[amount - coin] != -1 && min[amount - coin] + 1 < min_count) {
                min_count = min[amount - coin] + 1;
            }
        }
    }
    min[amount] = (min_count == Integer.MAX_VALUE ? -1 : min_count);
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值