1- from typing import List
1+ COINS = ( 200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 )
22cache = {}
33
44
@@ -8,34 +8,32 @@ def ways_to_make_change(total: int) -> int:
88
99 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.
1010 """
11- return ways_to_make_change_helper (total , [ 200 , 100 , 50 , 20 , 10 , 5 , 2 , 1 ] )
11+ return ways_to_make_change_helper (total , 0 )
1212
1313
14- def ways_to_make_change_helper (total : int , coins : List [ int ] ) -> int :
14+ def ways_to_make_change_helper (total : int , coin_index : int ) -> int :
1515 """
1616 Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1717 """
18- key = (total , tuple ( coins ) )
18+ key = (total , coin_index )
1919
2020 if key in cache :
2121 return cache [key ]
2222
23- if total == 0 or len (coins ) == 0 :
23+ if total == 0 :
24+ return 1
25+
26+ if total < 0 or coin_index >= len (COINS ):
2427 return 0
2528
26- ways = 0
27- for coin_index in range (len (coins )):
28- coin = coins [coin_index ]
29- count_of_coin = 1
30- while coin * count_of_coin <= total :
31- total_from_coins = coin * count_of_coin
32- if total_from_coins == total :
33- ways += 1
34- else :
35- intermediate = ways_to_make_change_helper (total - total_from_coins , coins = coins [coin_index + 1 :])
36- ways += intermediate
37- count_of_coin += 1
29+ coin = COINS [coin_index ]
30+
31+ # Option 1: Skip this coin and move to the next denomination.
32+ ways = ways_to_make_change_helper (total , coin_index + 1 )
33+
34+ # Option 2: Use this coin and consider it again.
35+ if coin <= total :
36+ ways += ways_to_make_change_helper (total - coin , coin_index )
3837
3938 cache [key ] = ways
4039 return ways
41-
0 commit comments