1- from typing import List
1+ from typing import List , Tuple , Dict
22
33
44def ways_to_make_change (total : int ) -> int :
@@ -7,26 +7,33 @@ 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+ coins = [200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ]
11+ cache : Dict [Tuple [int , int ], int ] = {}
12+ return ways_to_make_change_helper (total , coins , 0 , cache )
1113
1214
13- def ways_to_make_change_helper (total : int , coins : List [int ]) -> int :
15+ def ways_to_make_change_helper (
16+ total : int , coins : List [int ], coin_index : int , cache : Dict [Tuple [int , int ], int ]
17+ ) -> int :
1418 """
1519 Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1620 """
17- if total == 0 or len (coins ) == 0 :
21+ if total == 0 :
22+ return 1
23+ if total < 0 or coin_index == len (coins ):
1824 return 0
1925
26+ key = (total , coin_index )
27+ if key in cache :
28+ return cache [key ]
29+
30+ coin = coins [coin_index ]
2031 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
32+ count = 0
33+ while count * coin <= total :
34+ remaining = total - count * coin
35+ ways += ways_to_make_change_helper (remaining , coins , coin_index + 1 , cache )
36+ count += 1
37+
38+ cache [key ] = ways
3239 return ways
0 commit comments