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