AAlgoLoopSpaced repetition for LeetCode
MEDIUMDynamic ProgrammingLeetCode ↗

Coin Change II

The key idea

Count combinations, not permutations: loop over coins on the OUTSIDE and amounts on the INSIDE. Fixing the coin order means 1+2 and 2+1 are never counted twice. dp[x] accumulates the number of ways to make x using only the coins processed so far, and dp[x] += dp[x - coin] reuses each coin unlimited times.

Problem

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.

Constraints

Examples

Input: amount = 5, coins = [1,2,5] Output: 4
Input: amount = 3, coins = [2] Output: 0
Input: amount = 10, coins = [10] Output: 1

Complexity

Time: O(n * amount) Space: O(amount)

See the full solution

410310
Step-by-step visualization
Start free →

More Dynamic Programming problems