@@ -7,21 +7,29 @@ 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 ])
1110
11+ coins = [200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ]
12+ all_subarrays = []
13+ for i in range (len (coins )) :
14+ all_subarrays .append ( coins [i :] )
1215
13- def ways_to_make_change_helper (total : int , coins : List [int ],cache = None ) -> int :
16+ cache = {}
17+
18+ return ways_to_make_change_helper (total , all_subarrays ,0 ,cache )
19+
20+
21+ def ways_to_make_change_helper (total : int , all_subarrays : List [List [int ]],subarray_id : int ,cache ) -> int :
1422 """
1523 Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1624 """
17- if total == 0 or len (coins ) == 0 :
25+ if total == 0 or subarray_id >= len (all_subarrays ) :
1826 return 0
19- if cache is None :
20- cache = {}
21- key = (total ,tuple (coins ))
27+
28+ key = (total , subarray_id )
2229 if key in cache :
2330 return cache [key ]
2431
32+ coins = all_subarrays [subarray_id ]
2533 ways = 0
2634 for coin_index in range (len (coins )):
2735 coin = coins [coin_index ]
@@ -31,8 +39,10 @@ def ways_to_make_change_helper(total: int, coins: List[int],cache=None) -> int:
3139 if total_from_coins == total :
3240 ways += 1
3341 else :
34- intermediate = ways_to_make_change_helper (total - total_from_coins , coins = coins [ coin_index + 1 :], cache = cache )
35- ways += intermediate
42+ ways + = ways_to_make_change_helper (total - total_from_coins , all_subarrays , subarray_id + coin_index + 1 , cache )
43+
3644 count_of_coin += 1
37- cache [key ]= ways
45+
46+ cache [key ]= ways
47+
3848 return ways
0 commit comments