算法: 零钱兑换的方法数518. Coin Change 2

Posted AI架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 零钱兑换的方法数518. Coin Change 2相关的知识,希望对你有一定的参考价值。

518. Coin Change 2

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

You may assume that you have an infinite number of each kind of coin.

The answer is guaranteed to fit into a signed 32-bit integer.

Example 1:

Input: amount = 5, coins = [1,2,5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1

Example 2:

Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.

Example 3:

Input: amount = 10, coins = [10]
Output: 1

Constraints:

  • 1 <= coins.length <= 300
  • 1 <= coins[i] <= 5000
  • All the values of coins are unique.
  • 0 <= amount <= 5000

01背包问题动态规划解法

dp[i][j]:j使用第一种i类型的硬币组成的组合数
状态转移过程:

  1. 不使用i第一个硬币,只使用第一个i-1硬币来弥补金额j,然后我们有 dp[i-1][j]办法。
  2. 使用第i 个硬币,因为我们可以无限使用相同的硬币,所以我们需要知道j - coins[i-1]使用第一个i硬币(包括i)有多少种方式来弥补金额,即dp[i][j-coins[i-1]]

初始化: dp[i][0] = 1

一旦你弄清楚了所有这些,就很容易写出代码:

class Solution 
    public int change(int amount, int[] coins) 
        int n = coins.length;
        int[][] dp = new int[n + 1][amount + 1];
        dp[0][0] = 1;
        for (int c = 1; c <= n; c++) 
            dp[c][0] = 1;
            for (int i = 1; i <= amount; i++) 
                dp[c][i] = dp[c - 1][i] + (i >= coins[c - 1] ? dp[c][i - coins[c - 1]] : 0);
            
        
        
        return dp[n][amount];
    

参考

https://leetcode.com/problems/coin-change-2/discuss/99212/Knapsack-problem-Java-solution-with-thinking-process-O(nm)-Time-and-O(m)-Space

以上是关于算法: 零钱兑换的方法数518. Coin Change 2的主要内容,如果未能解决你的问题,请参考以下文章

518. 零钱兑换 II -- LeetCode -- 6.10

leetcode经典动态规划题目:518零钱兑换

[M背包] lc518. 零钱兑换 II(完全背包+背包求方案数)

java刷题--518零钱兑换II

LeetCode 0518. 零钱兑换 II

动态规划——详解leetcode518 零钱兑换 II