本题当amount为0时,无论有没有硬币、几个硬币,都算有一种方案
当没有硬币时,除非amount为0,否则0种方案
// 背包问题空间优化的动态规划,2ms,faster than 100%
class Solution {
public int change(int amount, int[] coins) {
int[] dp = new int[amount + 1];
dp[0] = 1;
for (int i : coins)
for (int j = i; j <= amount; j++)
dp[j] += dp[j - i];
return dp[amount];
}
}
// 普通动态规划背包问题,6ms,faster than 44.95%
class Solution {
public int change(int amount, int[] coins) {
int[][] dp = new int[coins.length + 1][amount + 1];
dp[0][0] = 1;
for (int i = 1; i <= coins.length; i++) {
dp[i][0] = 1;
for (int j = 1; j <= amount; j++)
dp[i][j] = dp[i - 1][j] + (j >= coins[i - 1] ? dp[i][j - coins[i - 1]] : 0);
}
return dp[coins.length][amount];
}
}
// recursion + mem,会Time Limit Exceeded
class Solution {
public int change(int amount, int[] coins) {
int[][] mem = new int[coins.length + 1][amount + 1];
return helper(amount, coins, coins.length, mem);
}
private int helper(int amount, int[] coins, int pos, int[][] mem) {
if (amount == 0)
return 1;
if (pos == 0)
return 0;
if (mem[pos][amount] != 0)
return mem[pos][amount];
mem[pos][amount] = helper(amount, coins, pos - 1, mem) + (amount >= coins[pos - 1] ? helper(amount - coins[pos - 1], coins, pos, mem) : 0);
return mem[pos][amount];
}
}