您的位置:首页 > 其它

Leetcode 322. Coin Change

2016-06-22 05:30 387 查看


322. Coin Change

Total Accepted: 25730 Total
Submissions: 102022 Difficulty: Medium

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.

很简单的一题犯了致命错误,俩小时没做出来。

一看是极值,并且最优化,有重复case,肯定是DP。然而犯了一个致命错误:博主由上至下做了,也就是由结果出发的。直接导致无法判断什么时候最优,于是写代码认为先取最大的,然后依次填满,只要能得到0就是最优。过了一半的case,然后剩下的case博主明白了,有可能一个数组就4个数,那么有可能3,4值差不多,但是如果选了3,能选比1大很多的2,这样结果就可能不一样了。比如:[83, 186, 408, 419] 6249。

就觉得这题挺简单的,思路很明了DP,但是DP是从基本到结果的!!!由底至上。。。看了这个blog人家说此题太水,博主一脸黑线。。

public class Solution { // 23ms
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount+1];
for(int i = 1; i <= amount;  i++){
dp[i] = Integer.MAX_VALUE;
}

for(int i = 0; i <= amount; i++){
for(int j = 0; j < coins.length; j++){
if(dp[i] != Integer.MAX_VALUE && i + coins[j] <= amount)
dp[i + coins[j]] = Math.min(dp[i] + 1, dp[i + coins[j]]);
}
}
return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
}
}


自己写了很久的错误版本怎么能扔,又是排序又是copy数组的,果断留念:

public class Solution {
public int coinChange(int[] coins, int amount) {
int last = coins.length-1; int[] newcoins;
Arrays.sort(coins);

if(amount == 0) return 0;
if(amount < coins[0]) return -1;
while(coins[last] > amount) last--;

int[] newcoin = Arrays.copyOfRange(coins, 0, last+1);
int[] dp = new int[amount+1];
for(int i : newcoin){
dp[i] = 1;
}
helper(newcoin, amount, dp);
return dp[amount] == 0 ? -1 : dp[amount];
}

void helper(int[] coins, int amount, int[] dp){
for(int i = coins.length-1; i>=0; i--){
if(coins[i] > amount) continue;

if(amount - coins[i]==0) {
dp[amount]=1; return;
}

if(dp[amount - coins[i]] == 0) helper(coins, amount-coins[i], dp);
if(dp[amount - coins[i]]!=0) {
dp[amount] = dp[amount-coins[i]] + 1; return;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Dynamic Programming