Coin Change
题目地址:
https://leetcode.com/problems/coin-change/description/
题目:
解题思路:
这道题应该用动态规划的思想。
代码:
https://leetcode.com/problems/coin-change/description/
题目:
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 =
return
coins =
[1, 2, 5], amount = 11return
3 (11 = 5 + 5 + 1)
Example 2:
coins =
return
coins =
[2], amount = 3return
-1.
Note:
You may assume that you have an infinite number of each kind of coin.
You may assume that you have an infinite number of each kind of coin.
解题思路:
这道题应该用动态规划的思想。
代码:
public int coinChange(int[] coins, int amount) { int[] dp = new int[amount + 1]; // the dp[0] has to be 0 for(int i = 1; i <= amount; i++){ int min = Integer.MAX_VALUE; for(int c : coins){ // update the min when needed if(i - c >= 0 && dp[i - c] != -1){ min = Math.min(min, dp[i - c] + 1); } } dp[i] = min == Integer.MAX_VALUE ? -1 : min; } return dp[amount]; }

Comments
Post a Comment