#518

Coin Change II

Medium
ArrayDynamic ProgrammingDynamic ProgrammingCombinatorial Counting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n)
💡

Intuition

Time O(n * m)Space O(n)

The optimal solution uses dynamic programming to build up the number of ways to reach each amount from 0 to the target amount. We use an array to store the number of combinations for each amount, updating it as we iterate through the coin denominations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a dp array of size (amount + 1) with dp[0] = 1 (base case).
  2. 2Step 2: For each coin, update the dp array for all amounts from the coin value to the target amount.
  3. 3Step 3: For each amount, add the number of combinations from the current coin to the previous amounts.
solution.py9 lines
1# Full working Python code
2
3def coinChangeII(amount, coins):
4    dp = [0] * (amount + 1)
5    dp[0] = 1
6    for coin in coins:
7        for x in range(coin, amount + 1):
8            dp[x] += dp[x - coin]
9    return dp[amount]

Complexity note: The time complexity is O(n * m) where n is the amount and m is the number of coin denominations. We iterate through each coin and update the dp array for each amount up to the target.

  • 1Dynamic programming can significantly reduce the time complexity of combinatorial problems.
  • 2Understanding how to build solutions incrementally is crucial in dynamic programming.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.