MediumArrayDynamic Programming

Coin Change II

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now