Coin Change

来源:互联网 发布:live for speed mac 编辑:程序博客网 时间:2024/06/05 16:38

题目描述:

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






0 0
原创粉丝点击