11from typing import List
22
3-
43def ways_to_make_change (total : int ) -> int :
5- """
6- Given access to coins with the values 1, 2, 5, 10, 20, 50, 100, 200, returns a count of all of the ways to make the passed total value.
7-
8- 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.
9- """
10- return ways_to_make_change_helper (total , [200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ])
4+ cache = {}
5+ return ways_to_make_change_helper (total , (200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ), cache )
116
12-
13- def ways_to_make_change_helper (total : int , coins : List [int ]) -> int :
14- """
15- Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
16- """
7+ def ways_to_make_change_helper (total : int , coins : tuple , cache : dict ) -> int :
178 if total == 0 or len (coins ) == 0 :
189 return 0
19-
10+ cache_key = (total , coins )
11+ if cache_key in cache :
12+ return cache [cache_key ]
2013 ways = 0
2114 for coin_index in range (len (coins )):
2215 coin = coins [coin_index ]
@@ -26,7 +19,12 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2619 if total_from_coins == total :
2720 ways += 1
2821 else :
29- intermediate = ways_to_make_change_helper (total - total_from_coins , coins = coins [coin_index + 1 :])
22+ intermediate = ways_to_make_change_helper (
23+ total - total_from_coins ,
24+ coins = coins [coin_index + 1 :],
25+ cache = cache
26+ )
3027 ways += intermediate
3128 count_of_coin += 1
32- return ways
29+ cache [cache_key ] = ways
30+ return ways
0 commit comments