|
1 | 1 | from typing import List |
2 | 2 |
|
| 3 | +cache = {} |
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 | + return ways_to_make_change_helper(total, (200, 100, 50, 20, 10, 5, 2, 1)) |
7 | 7 |
|
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 | | - |
12 | | - |
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: |
| 8 | +def ways_to_make_change_helper(total: int, coins) -> int: |
| 9 | + key = (total, coins) |
| 10 | + if key in cache: |
| 11 | + return cache[key] |
| 12 | + |
| 13 | + if total == 0: |
| 14 | + return 1 |
| 15 | + if len(coins) == 0: |
18 | 16 | return 0 |
19 | 17 |
|
20 | 18 | ways = 0 |
21 | | - for coin_index in range(len(coins)): |
22 | | - coin = coins[coin_index] |
23 | | - count_of_coin = 1 |
24 | | - while coin * count_of_coin <= total: |
25 | | - total_from_coins = coin * count_of_coin |
26 | | - if total_from_coins == total: |
27 | | - ways += 1 |
28 | | - else: |
29 | | - intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:]) |
30 | | - ways += intermediate |
31 | | - count_of_coin += 1 |
| 19 | + coin = coins[0] |
| 20 | + for count in range(total // coin + 1): |
| 21 | + intermediate = ways_to_make_change_helper(total - coin * count, coins[1:]) |
| 22 | + ways += intermediate |
| 23 | + |
| 24 | + cache[key] = ways |
32 | 25 | return ways |
0 commit comments