Leetcode之CoinChange
2016-10-17 09:58
253 查看
题目
题目地址 https://leetcode.com/problems/coin-change/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.
解题
典型的动态规划问题,满足最优子结构和重复子问题。定义问题的最优解:即当零钱为amount时最少需要哪些硬币。
最优解的值为:零钱为amount时候的最少硬币数。
递归式求解:令f[i]为当amount为i时最少需要的硬币数,则对于某一个coin[j]满足,i>=coin[j] 则剩余的零钱数为i-coin[j],硬币数+1。递归式可写成如下:
f[i] = Math.min(f[i],f[i-coin[j]]+1);
定义初始值:f[0]=0。
Code
/** * Created by bamboo on 2016/10/17. */ public class CoinChange { /** * 找出零钱为amount时候最少需要的硬币数 * @param coins * @param amount * @return */ public int coinChange(int[] coins, int amount) { int[] f = new int[amount + 1]; f[0] = 0; for (int i = 1; i <= amount; i++) { f[i] = Integer.MAX_VALUE; for (int j = 0; j < coins.length; j++) { /*满足计算条件*/ if (i >= coins[j] && f[i - coins[j]] != Integer.MAX_VALUE) { f[i] = Math.min(f[i], f[i - coins[j]] + 1); } } } return f[amount] == Integer.MAX_VALUE ? -1 : f[amount]; } }
令人意外超过居然达到了80%,特此纪念
相关文章推荐
- LeetCode "Coin Change"
- Leetcode (322) Coin Change
- Leetcode:Coin Change 2
- LeetCode Coin Change
- DP问题:leetcode(322) Coin Change
- LeetCode.322(518) Coin Change && Coin Change2
- leetcode Coin Change
- 322 LeetCode Coin Change
- Coin Change - leetcode 322号题目个人题解
- leetcode之Coin Change
- LeetCode Coin Change
- leetcode322 coin change & leetcode343 integer break
- leetcode Coin Change
- LeetCode之Coin Change 和 Coin Change 2
- LeetCode 322 Coin Change (完全背包)
- UVA - 674 Coin Change(完全背包)
- 322. Coin Change
- [Leetcode] 322. Coin Change 解题报告
- Light oj 1231 - Coin Change (I)(dp)
- 322. Coin Change