Problem description

You are given an integer amount representing a total amount of money, and an array of distinct coin denominations. You have an unlimited number of coins of each denomination.

Count how many distinct combinations of coins add up exactly to amount. Two combinations are considered the same if they use the same multiset of coins, so ordering does not matter (using coins 1 then 2 is the same combination as 2 then 1).

Return that count. If no combination can make up the amount, return 0. There is always exactly one way to make amount 0: use no coins.

Example 1

Input: amount = 5, coins = [1,2,5]

Output: 4

The combinations are 5, 2+2+1, 2+1+1+1, and 1+1+1+1+1, giving four distinct ways.

Example 2

Input: amount = 3, coins = [2]

Output: 0

With only coins of value 2 you can never reach an odd total like 3, so there are zero combinations.

Constraints

  • 1 <= coins.length <= 300
  • 1 <= coins[i] <= 5000
  • All values in coins are distinct
  • 0 <= amount <= 5 * 10^3

After the pattern

Now solve one you haven't seen.

Ribbon Spool Assemblies is our own problem on the technique behind Coin Change II: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free