Leetcode 322. Coin Change
2016-06-22 05:30
387 查看
322. Coin Change
Total Accepted: 25730 TotalSubmissions: 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; } } } }
相关文章推荐
- MyEclipse Web Project转Eclipse Dynamic Web Project
- DLL(Dynamic Linkable Library) 详解说明
- 深入C# 4.0 新特性dynamic、可选参数、命名参数的详细介绍
- C# Dynamic关键字之:解析dynamic就是Object
- C# Dynamic关键字之:dynamic为什么比反射快的详解
- Dynamic和Var的区别及dynamic使用详解
- C# dynamic关键字的使用方法
- PHP Warning: PHP Startup: Unable to load dynamic library \ D:/php5/ext/php_mysqli.dll\
- MariaDB扩展特性--动态列
- jenkins动态参数构建
- 编程语言进化
- DHCP Snooping + Dynamic ARP Inspection(DAI) 配置
- 架设动态 DNS 服务器: 让你成为 ISP 啦
- 关于php-fpm子进程设置
- 建立C语言动态链接库
- php-fpm的max_chindren的一些误区
- NSDictionary
- hyperv 动态磁盘的缺陷
- 五个编程语言设计的失误
- 编程语言时间地理图