@@ -7,26 +7,35 @@ def ways_to_make_change(total: int) -> int:
77
88 For instance, there are two ways to make a value of 3: with 3x 1 coins, or with 1x 1 coin and 1x 2 coin.
99 """
10- return ways_to_make_change_helper (total , [200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ])
10+ cache = {}
11+ return ways_to_make_change_helper (total , [200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ], 0 , cache )
1112
1213
13- def ways_to_make_change_helper (total : int , coins : List [int ]) -> int :
14+ def ways_to_make_change_helper (
15+ total : int , coins : List [int ], coin_index : int , cache : dict
16+ ) -> int :
1417 """
1518 Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1619 """
17- if total == 0 or len (coins ) == 0 :
20+ if total == 0 :
21+ return 1
22+ if coin_index == len (coins ):
1823 return 0
1924
25+ key = (total , coin_index )
26+ if key in cache :
27+ return cache [key ]
28+
29+ coin = coins [coin_index ]
2030 ways = 0
21- for coin_index in range (len (coins )):
22- coin = coins [coin_index ]
23- count_of_coin = 1
24- while coin * count_of_coin <= total :
25- total_from_coins = coin * count_of_coin
26- if total_from_coins == total :
27- ways += 1
28- else :
29- intermediate = ways_to_make_change_helper (total - total_from_coins , coins = coins [coin_index + 1 :])
30- ways += intermediate
31- count_of_coin += 1
31+
32+ # the remaining coins can complete whatever total is left over
33+ while coin * count <= total :
34+ ways += ways_to_make_change_helper (total - coin * count , coins , coin_index + 1 , cache )
35+ count += 1
36+
37+ # counting combinations that don't use the current coin
38+ ways += ways_to_make_change_helper (total , coins , coin_index + 1 , cache )
39+
40+ cache [key ] = ways
3241 return ways
0 commit comments