2017-10-25 01:56:48 +00:00
|
|
|
"""
|
|
|
|
You have m types of coins available in infinite quantities
|
|
|
|
where the value of each coins is given in the array S=[S0,... Sm-1]
|
|
|
|
Can you determine number of ways of making change for n units using
|
2017-10-25 07:58:46 +00:00
|
|
|
the given types of coins?
|
2017-10-25 01:56:48 +00:00
|
|
|
https://www.hackerrank.com/challenges/coin-change/problem
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
def dp_count(s, n):
|
2019-12-18 07:35:03 +00:00
|
|
|
"""
|
2020-10-23 16:55:13 +00:00
|
|
|
>>> dp_count([1, 2, 3], 4)
|
2019-12-18 07:35:03 +00:00
|
|
|
4
|
2020-10-23 16:55:13 +00:00
|
|
|
>>> dp_count([1, 2, 3], 7)
|
2019-12-18 07:35:03 +00:00
|
|
|
8
|
2020-10-23 16:55:13 +00:00
|
|
|
>>> dp_count([2, 5, 3, 6], 10)
|
2019-12-18 07:35:03 +00:00
|
|
|
5
|
2020-10-23 16:55:13 +00:00
|
|
|
>>> dp_count([10], 99)
|
2019-12-18 07:35:03 +00:00
|
|
|
0
|
2020-10-23 16:55:13 +00:00
|
|
|
>>> dp_count([4, 5, 6], 0)
|
2019-12-18 07:35:03 +00:00
|
|
|
1
|
2020-10-23 16:55:13 +00:00
|
|
|
>>> dp_count([1, 2, 3], -5)
|
|
|
|
0
|
2019-12-18 07:35:03 +00:00
|
|
|
"""
|
2020-10-23 16:55:13 +00:00
|
|
|
if n < 0:
|
|
|
|
return 0
|
2019-02-20 16:54:26 +00:00
|
|
|
# table[i] represents the number of ways to get to amount i
|
2017-10-25 01:56:48 +00:00
|
|
|
table = [0] * (n + 1)
|
|
|
|
|
2019-02-20 16:54:26 +00:00
|
|
|
# There is exactly 1 way to get to zero(You pick no coins).
|
2017-10-25 01:56:48 +00:00
|
|
|
table[0] = 1
|
|
|
|
|
|
|
|
# Pick all coins one by one and update table[] values
|
|
|
|
# after the index greater than or equal to the value of the
|
|
|
|
# picked coin
|
2022-10-12 22:54:20 +00:00
|
|
|
for coin_val in s:
|
2019-02-20 16:54:26 +00:00
|
|
|
for j in range(coin_val, n + 1):
|
|
|
|
table[j] += table[j - coin_val]
|
2017-10-25 01:56:48 +00:00
|
|
|
|
|
|
|
return table[n]
|
|
|
|
|
2019-12-26 11:50:12 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2019-12-18 07:35:03 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|