|
1 | 1 | """
|
2 | 2 | Problem
|
3 |
| -Given a value n, if we want to make change for N cents, and we have infinite supply of each of |
4 |
| -coins = {S1, S2, .. , Sm} valued coins, how many ways can we make the change? |
| 3 | +Given a value n, if we want to make change for N cents, |
| 4 | +and we have infinite supply of each of |
| 5 | +coins = {S1, S2, .. , Sm} valued coins, how many ways |
| 6 | +can we make the change? |
5 | 7 | The order of coins doesn't matter.
|
6 |
| -For example, for n = 4 and coins = [1, 2, 3], there are four solutions: |
7 |
| -[1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3]. |
8 |
| -So output should be 4. |
| 8 | +For example, for n = 4 and coins = [1, 2, 3], there are |
| 9 | +four solutions: |
| 10 | +[1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3]. |
| 11 | +So output should be 4. |
9 | 12 |
|
10 |
| -For n = 10 and coins = [2, 5, 3, 6], there are five solutions: |
11 |
| -[2, 2, 2, 2, 2], [2, 2, 3, 3], [2, 2, 6], [2, 3, 5] and [5, 5]. |
| 13 | +For n = 10 and coins = [2, 5, 3, 6], there are five solutions: |
| 14 | +[2, 2, 2, 2, 2], [2, 2, 3, 3], [2, 2, 6], [2, 3, 5] and [5, 5]. |
12 | 15 | So the output should be 5.
|
13 | 16 |
|
14 | 17 | Time complexity: O(n * m) where n is the value and m is the number of coins
|
15 | 18 | Space complexity: O(n)
|
16 | 19 | """
|
17 | 20 |
|
| 21 | + |
18 | 22 | def count(coins, n):
|
19 | 23 | # initialize dp array and set base case as 1
|
20 | 24 | dp = [1] + [0] * n
|
21 |
| - |
| 25 | + |
22 | 26 | # fill dp in a bottom up manner
|
23 | 27 | for coin in coins:
|
24 | 28 | for i in range(coin, n+1):
|
25 | 29 | dp[i] += dp[i-coin]
|
26 | 30 |
|
27 | 31 | return dp[n]
|
28 |
| - |
|
0 commit comments