Skip to content

Commit fbd3ba6

Browse files
committed
Update 322-coin_change.py
1 parent 8ef5c7b commit fbd3ba6

File tree

1 file changed

+24
-21
lines changed

1 file changed

+24
-21
lines changed

322-coin_change.py

+24-21
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,42 @@
11
"""
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.
310
"""
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:
1113
memo = {}
1214

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+
1420
#base cases
1521
if amount_left == 0:
16-
return coins_used
22+
return 0
1723
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')
2425

2526
#recursive cases
26-
best = sys.maxint
27+
best = float('inf')
2728
for coin in coins:
28-
coins_needed = dp_helper(amount_left - coin, coins_used + 1)
29+
coins_needed = 1 + solve(amount_left - coin)
2930
best = min(best, coins_needed)
3031

3132
#memoize the result for future use
32-
memo[(amount_left, coins_used)] = best
33+
memo[amount_left] = best
3334
return best
35+
#--------------end helper function--------------
36+
3437

35-
result = dp_helper(amount, 0)
36-
if result == sys.maxint:
38+
result = solve(amount)
39+
if result == float('inf'):
3740
return -1
3841
else:
3942
return result

0 commit comments

Comments
 (0)