leetcode322 零钱兑换

21 阅读1分钟

直接用dp[j]来表示凑成金额j所需的最小硬币数的状态

322. 零钱兑换 - 力扣(LeetCode)


class Solution {
    public int coinChange(int[] coins, int amount) {
        // 定义dp[j] 为 凑成金额j所需的最小硬币数
        // 初始化 dp数组长度为 amount+1,然后dp[]也都初始化为不可能的大数amount+1,dp[0] = 0 凑0元需0个硬币
        // 状态转移 完全背包 正序遍历  dp[j] = min(dp[j], dp[j-coin]+1)
        // 若dp[amount] > amount 说明无法凑成返回-1
        int[] dp = new int[amount+1];
        Arrays.fill(dp, amount+1);
        dp[0] = 0;
        for(int i = 0; i < coins.length; i++) {
            if(coins[i] > amount) continue;
            for(int j = coins[i]; j <= amount; j++) {
                dp[j] = Math.min(dp[j], dp[j-coins[i]]+1);
            }
        }
        return dp[amount] == amount+1 ? -1 : dp[amount]; 
    }
}