链接: https://leetcode-cn.com/problems/coin-change/
经典动态规划问题
构成 amount 的方案数一定可以由他的子问题来解决;构建递归树的过程中发现有重叠子问题 -》 动态规划
步骤:
分析状态:什么在改变 -》 amount
选择是什么: amount - coins[i]
转移方程: dp[i] = min (
amount - coins[i])
方案一:递归
class Solution {
public int coinChange(int[] coins, int amount) {
if (amount == 0) return 0;
if (amount < 0) return -1;
// 函数定义:构成amount 硬币的最小数量
int res = amount + 1;
for (int coin : coins) {
res = Math.min(res, coinChange(coins, amount - coin));
}
return res == amount + 1 ? -1 : res;
}
}
完整递归树的过程,但是中间有很多结点是重复计算的,可以使用备忘录
方案二:备忘录
class Solution {
private int[] memo;
public int coinChange(int[] coins, int amount) {
if (memo == null) {
memo = new int[amount + 1];
Arrays.fill(memo, Integer.MAX_VALUE);
}
if (amount == 0) return 0;
if (amount < 0) return -1;
if (memo[amount] != Integer.MAX_VALUE) return memo[amount];
// 函数定义:构成amount 硬币的最小数量
int res = amount + 1;
for (int coin : coins) {
int subSequence = coinChange(coins, amount - coin);
if (subSequence == -1) continue;
res = Math.min(res, subSequence + 1);
}
memo[amount] = res == amount + 1 ? -1 : res;
return memo[amount];
}
}
可以通过,然后动态规划就是在这个基础上 改为自底向上的迭代
方案三:迭代
class Solution {
private int[] memo;
public int coinChange(int[] coins, int amount) {
if (amount == 0) return 0;
memo = new int[amount + 1];
Arrays.fill(memo, amount + 1);
memo[0] = 0;
for (int k = 0; k <= amount; k ++) {
for (int i = 0; i < coins.length; i++) {
if (k < coins[i]) continue;
memo[k] = Math.min(memo[k], memo[k - coins[i]] + 1);
}
}
return (memo[amount] == amount + 1) ? -1 : memo[amount];
}
}