Coin Change II — LeetCode 518 Python Solution
- Problem
- #518
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- amount = 5, coins = [1,2,5]
- Output
- 4
- Explanation
- there are four ways to make up the amount:
Python solution
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
m, n = len(coins), amount
f = [[0] * (n + 1) for _ in range(m + 1)]
f[0][0] = 1
for i, x in enumerate(coins, 1):
for j in range(n + 1):
f[i][j] = f[i - 1][j]
if j >= x:
f[i][j] += f[i][j - x]
return f[m][n]Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(m \times n) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 518. Coin Change II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
On a study list
This problem is on NeetCode 150.
Frequently asked questions
- How hard is LeetCode 518. Coin Change II?
- LeetCode 518. Coin Change II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 518. Coin Change II?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 518. Coin Change II?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 518. Coin Change II cover?
- LeetCode 518. Coin Change II is tagged Array and Dynamic Programming on LeetCode.