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