11from typing import List
22
3-
43def ways_to_make_change (total : int ) -> int :
54 """
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.
5+ Given access to coins with the values 1, 2, 5, 10, 20, 50, 100, 200,
6+ returns a count of all of the ways to make the passed total value.
97 """
10- return ways_to_make_change_helper (total , [200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ])
8+ cache = {}
9+ return ways_to_make_change_helper (total , [200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ], cache )
1110
1211
13- def ways_to_make_change_helper (total : int , coins : List [int ]) -> int :
12+ def ways_to_make_change_helper (total : int , coins : List [int ], cache : dict ) -> int :
1413 """
15- Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
14+ Helper function with memoization.
15+ Cache key is (total, index of first coin in list) — but since we pass
16+ the coins list by slicing, we can cache using tuple(total, tuple(coins)).
1617 """
18+
19+ key = (total , tuple (coins ))
20+
21+ if key in cache :
22+ return cache [key ]
23+
1724 if total == 0 or len (coins ) == 0 :
1825 return 0
1926
@@ -26,7 +33,13 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2633 if total_from_coins == total :
2734 ways += 1
2835 else :
29- intermediate = ways_to_make_change_helper (total - total_from_coins , coins = coins [coin_index + 1 :])
36+ intermediate = ways_to_make_change_helper (
37+ total - total_from_coins ,
38+ coins = coins [coin_index + 1 :],
39+ cache = cache
40+ )
3041 ways += intermediate
3142 count_of_coin += 1
32- return ways
43+
44+ cache [key ] = ways
45+ return ways
0 commit comments