程序员社区

LeetCode-322-零钱兑换

LeetCode-322-零钱兑换

322. 零钱兑换

难度中等

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1

你可以认为每种硬币的数量是无限的。

示例 1:

输入:coins = [1, 2, 5], amount = 11
输出:3 
解释:11 = 5 + 5 + 1

示例 2:

输入:coins = [2], amount = 3
输出:-1

示例 3:

输入:coins = [1], amount = 0
输出:0

示例 4:

输入:coins = [1], amount = 1
输出:1

示例 5:

输入:coins = [1], amount = 2
输出:2

提示:

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 231 - 1
  • 0 <= amount <= 104

题解思路-动态规划

LeetCode-322-零钱兑换插图
image-20210629105320415
LeetCode-322-零钱兑换插图1
image-20210629105857053
LeetCode-322-零钱兑换插图2
image-20210629110806659
LeetCode-322-零钱兑换插图3
image-20210629110853327
LeetCode-322-零钱兑换插图4
image-20210629110948397
LeetCode-322-零钱兑换插图5
image-20210629111211003
LeetCode-322-零钱兑换插图6
image-20210629111336560
LeetCode-322-零钱兑换插图7
image-20210629111501591
class Solution {
    public static int coinChange(int[] coins, int aim) {
        if (coins == null || coins.length == 0 || aim < 0) {
            return -1;
        }
        int N = coins.length;
        int[][] dp = new int[N][aim + 1];
        // dp[i][0] = 0 0列不需要填
        // dp[0][1...] = arr[0]的整数倍,有张数,倍数,其他的格子-1(表示无方案)
        for (int j = 1; j <= aim; j++) {
            if (j % coins[0] != 0) {
                dp[0][j] = -1;
            } else {
                dp[0][j] = j / coins[0];
            }
        }

        for (int i = 1; i < N; i++) {
            for (int j = 1; j <= aim; j++) {
                dp[i][j] = Integer.MAX_VALUE;
                if (dp[i - 1][j] != -1) {
                    dp[i][j] = dp[i - 1][j];
                }
                if (j - coins[i] >= 0 && dp[i][j - coins[i]] != -1) {
                    dp[i][j] = Math.min(dp[i][j], dp[i][j - coins[i]] + 1);
                }
                if (dp[i][j] == Integer.MAX_VALUE) {
                    dp[i][j] = -1;
                }
            }
        }
        return dp[N - 1][aim];
    }
}
LeetCode-322-零钱兑换插图8
image-20210629111542774
赞(0) 打赏
未经允许不得转载:IDEA激活码 » LeetCode-322-零钱兑换

一个分享Java & Python知识的社区