您的位置:首页 > 其它

Coin Change

2016-06-17 11:22 357 查看
题目描述:

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: