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