@@ -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+ coins = [200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ]
11+ memo = {}
12+ return ways_to_make_change_helper (total , coins , 0 , memo )
1113
12-
13- def ways_to_make_change_helper (total : int , coins : List [int ]) -> int :
14+ def ways_to_make_change_helper (total : int , coins : List [int ], coin_index : int , memo : dict ) -> int :
1415 """
1516 Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1617 """
17- if total == 0 or len (coins ) == 0 :
18+ if total == 0 :
19+ return 1
20+
21+ if coin_index == len (coins ):
1822 return 0
23+
24+ key = (total , coin_index )
25+
26+ if key in memo :
27+ return memo [key ]
28+
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+ coin = coins [coin_index ]
32+ count_of_coin = 0
33+
34+ while count_of_coin * coin <= total :
35+ remaining = total - count_of_coin * coin
36+ ways += ways_to_make_change_helper (remaining , coins , coin_index + 1 , memo )
37+ count_of_coin += 1
38+
39+ memo [key ] = ways
40+
3241 return ways
0 commit comments