|
1 | 1 | """
|
2 |
| -Time limit exceeded... but an attempt at top-down recursive |
| 2 | +Inspired by this really clean solution: |
| 3 | +https://leetcode.com/problems/coin-change/discuss/1679136/Python-Simplest-Recursive-Solution-with-Memoization |
| 4 | +
|
| 5 | +Strat: |
| 6 | + Recursive DP w/ Memoization |
| 7 | +Stats: |
| 8 | + Runtime: 2674 ms, faster than 20.15% of Python3 online submissions for Coin Change. |
| 9 | + Memory Usage: 44.4 MB, less than 5.47% of Python3 online submissions for Coin Change. |
3 | 10 | """
|
4 |
| -class Solution(object): |
5 |
| - def coinChange(self, coins, amount): |
6 |
| - """ |
7 |
| - :type coins: List[int] |
8 |
| - :type amount: int |
9 |
| - :rtype: int |
10 |
| - """ |
| 11 | +class Solution: |
| 12 | + def coinChange(self, coins: List[int], amount: int) -> int: |
11 | 13 | memo = {}
|
12 | 14 |
|
13 |
| - def dp_helper(amount_left, coins_used): |
| 15 | + def solve(amount_left): |
| 16 | + #see if solution has already been calculated |
| 17 | + if memo.get(amount_left): |
| 18 | + return memo[amount_left] |
| 19 | + |
14 | 20 | #base cases
|
15 | 21 | if amount_left == 0:
|
16 |
| - return coins_used |
| 22 | + return 0 |
17 | 23 | elif amount_left < 0:
|
18 |
| - return sys.maxint |
19 |
| - |
20 |
| - #see if solution has already been calculated |
21 |
| - if memo.get((amount_left, coins_used), -1) > 0: |
22 |
| - # print(memo.get((amount_left, coins_used))) |
23 |
| - return memo.get((amount_left, coins_used)) |
| 24 | + return float('inf') |
24 | 25 |
|
25 | 26 | #recursive cases
|
26 |
| - best = sys.maxint |
| 27 | + best = float('inf') |
27 | 28 | for coin in coins:
|
28 |
| - coins_needed = dp_helper(amount_left - coin, coins_used + 1) |
| 29 | + coins_needed = 1 + solve(amount_left - coin) |
29 | 30 | best = min(best, coins_needed)
|
30 | 31 |
|
31 | 32 | #memoize the result for future use
|
32 |
| - memo[(amount_left, coins_used)] = best |
| 33 | + memo[amount_left] = best |
33 | 34 | return best
|
| 35 | + #--------------end helper function-------------- |
| 36 | + |
34 | 37 |
|
35 |
| - result = dp_helper(amount, 0) |
36 |
| - if result == sys.maxint: |
| 38 | + result = solve(amount) |
| 39 | + if result == float('inf'): |
37 | 40 | return -1
|
38 | 41 | else:
|
39 | 42 | return result
|
0 commit comments