1. Description
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return 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.
You may assume that you have an infinite number of each kind of coin.
2. Test Cases
Example 1:
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Example 3:
Input: coins = [1], amount = 0
Output: 0
Example 4:
Input: coins = [1], amount = 1
Output: 1
Example 5:
Input: coins = [1], amount = 2
Output: 2
3. Solution
3.1 带备忘录递归
class Solution {
public int coinChange(int[] coins, int amount) {
Integer[] dp = new Integer[amount +1];
dp[0] = 0;
find(coins, amount, dp);
return dp[amount];
}
private int find(int[] coins, int amount, Integer[] dp) {
if (amount == 0) return 0;
if(dp[amount] != null )
return dp[amount];
int min =Integer.MAX_VALUE;
for (int c : coins) {
if (amount -c >= 0) {
int r = find(coins, amount-c, dp);
if (r != -1)
min = Math.min(min, r + 1);
}
}
return dp[amount] = (min == Integer.MAX_VALUE ? -1 : min);
}
}
3.2 iterative
class Solution {
public int coinChange(int[] coins, int amount) {
Integer[] dp = new Integer[amount +1];
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
int min = Integer.MAX_VALUE;
for (int c : coins) {
if (i - c >= 0 ) {
int r = dp[i - c];
if (r != -1)
min = Math.min(min, r + 1);
}
}
dp[i] = min == Integer.MAX_VALUE ? -1 : min;
}
return dp[amount];
}
}
4. 思考
似乎动态规划的本质就是穷举,只是如何穷举更少的次数,更快的得到结果。
本文介绍了如何使用动态规划算法解决寻找最少硬币组合的问题。通过递归和迭代两种方式实现,分别展示了带备忘录的递归解法和迭代解法。在给定的不同面额硬币及总金额条件下,找出组成该金额所需的最少硬币数。对于无法组成目标金额的情况,返回-1。动态规划的核心在于优化穷举过程,以减少计算次数并提高效率。
1907

被折叠的 条评论
为什么被折叠?



