518- change exchange II (full backpack - Evaluating the total)

518- change exchange II (full backpack - Evaluating the total)

Given the different denominations of coins and a total amount. Function can be written to calculate the number of coins to make up the total amount of the composition. Assuming that each denomination coin has an infinite number.

Example 1:

输入: amount = 5, coins = [1, 2, 5]
输出: 4
解释: 有四种方式可以凑成总金额:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1

Example 2:

输入: amount = 3, coins = [2]
输出: 0
解释: 只用面额2的硬币不能凑成总金额3。

Example 3:

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

note:

You can assume that:

  • 0 <= amount (total amount) <= 5000
  • 1 <= coin (coin denomination) <= 5000
  • No more than 500 kinds of types of coins
  • Results for 32-bit signed integer

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/coin-change-2
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

    public int change(int amount, int[] coins) {
        int[] f = new int[amount + 1];
        f[0] = 1;
        for (int coin : coins) {
            for (int v = coin; v <= amount; v++) {
                f[v] = f[v - coin] + f[v];
            }
        }
        return f[amount];
    }

Guess you like

Origin www.cnblogs.com/angelica-duhurica/p/12242583.html