322. 零钱兑换
1.状态定义
dp[i]代表凑齐总价值 i 需要的最少硬币个数;
2.状态转移方程
for(int coin : coins)
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
class Solution { public int coinChange(int[] coins, int amount) { int[]dp = new int[amount + 1]; //不可能用到amount+1个硬币,所以用它初始化数组 Arrays.fill(dp, amount + 1); dp[0] = 0; for(int i = 1; i <= amount; i++){ for(int coin : coins) if (i - coin >= 0) dp[i] = Math.min(dp[i], dp[i - coin] + 1); } //dp[amount]最开始被初始化为amount+1了,还为此值则代表无法变动 if (dp[amount] == amount + 1) { dp[amount] = -1; } return dp[amount]; } }