|
1 | | -from typing import List |
2 | | - |
| 1 | +from typing import List, Dict, Tuple |
3 | 2 |
|
4 | 3 | def ways_to_make_change(total: int) -> int: |
5 | 4 | """ |
6 | 5 | 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 | 6 |
|
8 | 7 | 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 | 8 | """ |
10 | | - return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1]) |
| 9 | + coins = [200, 100, 50, 20, 10, 5, 2, 1] |
| 10 | + memo: Dict[Tuple[int, int], int] = {} |
| 11 | + return ways_to_make_change_helper(total, coins, memo) |
11 | 12 |
|
12 | 13 |
|
13 | | -def ways_to_make_change_helper(total: int, coins: List[int]) -> int: |
| 14 | +def ways_to_make_change_helper(total: int, coins: List[int], memo: Dict[Tuple[int, int], int]) -> int: |
14 | 15 | """ |
15 | 16 | Helper function for ways_to_make_change to avoid exposing the coins parameter to callers. |
| 17 | + Uses memoization to cache results for (total, coin_index). |
16 | 18 | """ |
17 | | - if total == 0 or len(coins) == 0: |
18 | | - return 0 |
| 19 | + if total == 0: |
| 20 | + return 1 |
| 21 | + if total < 0 or not coins: |
| 22 | + return 0 |
| 23 | + |
| 24 | + key = (total, len(coins)) |
| 25 | + if key in memo: |
| 26 | + return memo[key] |
19 | 27 |
|
20 | 28 | ways = 0 |
21 | 29 | for coin_index in range(len(coins)): |
22 | 30 | coin = coins[coin_index] |
23 | 31 | count_of_coin = 1 |
24 | 32 | while coin * count_of_coin <= total: |
25 | | - total_from_coins = coin * count_of_coin |
26 | | - if total_from_coins == total: |
| 33 | + remainder = total - coin * count_of_coin |
| 34 | + if remainder == 0: |
27 | 35 | ways += 1 |
28 | 36 | else: |
29 | | - intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:]) |
30 | | - ways += intermediate |
| 37 | + ways += ways_to_make_change_helper(remainder, coins[coin_index + 1:], memo) |
31 | 38 | count_of_coin += 1 |
| 39 | + |
| 40 | + memo[key] = ways |
32 | 41 | return ways |
0 commit comments