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