LeetCode 322. Coin Change(零钱兑换)

Example 1:

Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1
Example 2:

Input: coins = [2], amount = 3
Output: -1

每种硬币的数量是无限的——完全背包问题

public int coinChange(int[] coins, int amount) {
        //dp[i]表示金额为i需要最少的硬币数
        int[] dp = new int[amount + 1];

        //处理:没有任何一种硬币组合能组成总金额,返回 -1 的情况
        Arrays.fill(dp, amount + 1);

        dp[0] = 0;
        for(int i = 1; i <= amount; i ++) {
            for(int j = 0; j < coins.length; j ++) {
                if(coins[j] <= i) {
                    dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
                }
            }
        }
        //如果没有任何一种硬币组合能组成总金额,返回 -1。
        return dp[amount] > amount? -1 : dp[amount];
    }
原创文章 626 获赞 104 访问量 32万+

猜你喜欢

转载自blog.csdn.net/gx17864373822/article/details/105419918
今日推荐