@@ -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+ return ways_to_make_change_helper (total , [200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ], coin_index = 0 , cache = None )
1111
1212
13- def ways_to_make_change_helper (total : int , coins : List [int ]) -> int :
13+ def ways_to_make_change_helper (total : int , coins : List [int ], coin_index : int = 0 , cache : dict = None ) -> int :
1414 """
1515 Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1616 """
17- if total == 0 or len (coins ) == 0 :
17+ if cache == None :
18+ cache = {}
19+
20+ current_key = (total , coin_index )
21+ if current_key in cache :
22+ return cache [current_key ]
23+
24+ if total == 0 :
25+ return 1
26+
27+ if total < 0 or coin_index >= len (coins ):
1828 return 0
1929
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+ remaining_value = total - coins [coin_index ]
33+
34+ taken_the_coin = ways_to_make_change_helper (remaining_value , coins , coin_index , cache )
35+
36+ left_the_coin = ways_to_make_change_helper (total , coins , coin_index + 1 , cache )
37+
38+ ways = taken_the_coin + left_the_coin
39+
40+ cache [current_key ] = ways
3241 return ways
0 commit comments