> For the complete documentation index, see [llms.txt](https://zedive.gitbook.io/project-l/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zedive.gitbook.io/project-l/part-2/dynamic_programming/knapsack/coin-change-2.md).

# Coin Change 2

## Question ([LC.518](https://leetcode.com/problems/coin-change-2/))&#x20;

> Given a list of coin denominations and a desired amount, find the number of combinations that make up that amount.&#x20;

## Examples

```
I: amount = 5, coins = [1,2,5]
O: 4 because [1,1,1,1,1], [1,1,1,2],[1,2,2],[5]

I: amount = 3, coins = [2]
O: 0 

I: amount = 10, coins = [10]
O: 1
```

## Approach&#x20;

```
# define by prefix 
# dp[i][a] = the number of combinations from coins[:i] to make up amount a 

# solve by prefix 
# choose to use the current coin (new combination) 
# not choose to use the current coin (existing combinations)
# for a from 0 to amount 
#     dp[i][a] = dp[i][a-coins[i]] + dp[i-1][a]

# base case 
# dp[0][0] = 1 (empty set to amount 0 has 1 combination) 

# topo order 
# for i from 0 to n 

# final answer 
# dp[n][amount]
```

## Code&#x20;

```python
def change(self, amount: int, coins: List[int]) -> int:
    n = len(coins)
    dp: List[List[int]] = [ [0] * (amount + 1) for _ in range(n + 1)] 
    
    # init 
    dp[0][0] = 1
    
    # topo order 
    for i in range(1, n + 1):
        coin_i = i - 1
        # solve by prefix 
        for a in range(amount + 1):
            dp[i][a] += dp[i-1][a]
            if a - coins[coin_i] >= 0:
                dp[i][a] += dp[i][a-coins[coin_i]]

    return dp[n][amount]
```

## Time Complexity&#x20;

time O(na) space O(na) but can be optimized to O(a)&#x20;


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zedive.gitbook.io/project-l/part-2/dynamic_programming/knapsack/coin-change-2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
