11from typing import List
22
33cache = {}
4+ coins = [1 , 2 , 5 , 10 , 20 , 50 , 100 , 200 ]
45
56def ways_to_make_change (total : int ) -> int :
67 """
78 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.
89
910 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.
1011 """
11- return ways_to_make_change_helper (total , [ 200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ] )
12+ return ways_to_make_change_helper (total , 0 )
1213
1314
1415
15- def ways_to_make_change_helper (total : int , coins : List [ int ] ) -> int :
16- key = (total , tuple ( coins ) )
16+ def ways_to_make_change_helper (total : int , index : int ) -> int :
17+ key = (total , index )
1718 if key in cache :
1819 return cache [key ]
1920 """
2021 Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
2122 """
22- if total == 0 or len (coins ) == 0 :
23- result = 0
24- cache [key ] = result
25- return result
26-
27- if total == 1 or len (coins ) == 1 :
28- result = 1
29- cache [key ] = result
30- return result
23+ if total == 0 :
24+ cache [key ] = 1
25+ return 1
26+
27+ if index == len (coins ):
28+ cache [key ] = 0
29+ return 0
3130
31+ coin = coins [index ]
3232 ways = 0
33- for coin_index in range (len (coins )):
34- coin = coins [coin_index ]
35- count_of_coin = 1
36- while coin * count_of_coin <= total :
37- total_from_coins = coin * count_of_coin
38- if total_from_coins == total :
39- ways += 1
40- else :
41- intermediate = ways_to_make_change_helper (total - total_from_coins , coins = coins [coin_index + 1 :])
42- ways += intermediate
43- count_of_coin += 1
44-
33+ count = 0
34+ while coin * count <= total :
35+ ways += ways_to_make_change_helper (total - coin * count , index + 1 )
36+ count += 1
4537 cache [key ] = ways
4638 return ways
0 commit comments