您的位置:首页 > 其它

322. Coin Change

2017-09-20 09:47 381 查看
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.

以前写的DP是

public class Solution {
public int coinChange(int[] coins, int amount) {
if(amount == 0)		return 0;
int[] dp = new int[amount+1];
Arrays.fill(dp, amount+1);
dp[0] = 0;

for(int i=1; i<=amount; i++) {
for(int coin : coins) {
if(i >= coin && dp[i-coin] != amount+1)
dp[i] = Math.min(dp[i-coin]+1, dp[i]);
}
}

return dp[amount] == amount+1 ? -1 : dp[amount];
}
}


现在写的是

import java.util.Arrays;

class Solution {
public int coinChange(int[] coins, int amount) {
// 到当前数组的i位置时,正好凑到j需要的最小步数
int MAX = 999999;
int[][] dp = new int[coins.length][amount+1];
for(int i=0; i<dp.length; i++)	Arrays.fill(dp[i], MAX);
for(int i=0; i<=amount; i+=coins[0])
dp[0][i] = i/coins[0];

for(int i=1; i<coins.length; i++) {
for(int j=0; j<=amount; j++) {
for(int k=0; k<=j/coins[i]; k++) {
dp[i][j] = Math.min(dp[i][j], dp[i-1][j-k*coins[i]]+k);
}
}
}

int min = MAX;
for(int i=0; i<coins.length; i++)
min = Math.min(min, dp[i][amount]);
return min == MAX ? -1 : min;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: