美文网首页
322. 零钱兑换

322. 零钱兑换

作者: justonemoretry | 来源:发表于2021-09-10 23:23 被阅读0次
image.png

解法

class Solution {
    public int coinChange(int[] coins, int amount) {
        // amount为j时,需要的最少金币数
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, amount + 1);
        // 初始化,amount为0时,
        dp[0] = 0;
        for (int i = 0; i < coins.length; i++) {
            for (int j = coins[i]; j <= amount; j++) {
                // 比较之前i - 1个时,不取当前元素,和取当前元素的最小值
                dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
            }
        }
        return dp[amount] > amount ? -1 : dp[amount]; 
    }
}

相关文章

网友评论

      本文标题:322. 零钱兑换

      本文链接:https://www.haomeiwen.com/subject/dnfowltx.html