-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0518-coin-change-ii.py
49 lines (43 loc) · 1.42 KB
/
0518-coin-change-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
# MEMOIZATION
# Time: O(n*m)
# Memory: O(n*m)
cache = {}
def dfs(i, a):
if a == amount:
return 1
if a > amount:
return 0
if i == len(coins):
return 0
if (i, a) in cache:
return cache[(i, a)]
cache[(i, a)] = dfs(i, a + coins[i]) + dfs(i + 1, a)
return cache[(i, a)]
return dfs(0, 0)
# DYNAMIC PROGRAMMING
# Time: O(n*m)
# Memory: O(n*m)
dp = [[0] * (len(coins) + 1) for i in range(amount + 1)]
dp[0] = [1] * (len(coins) + 1)
for a in range(1, amount + 1):
for i in range(len(coins) - 1, -1, -1):
dp[a][i] = dp[a][i + 1]
if a - coins[i] >= 0:
dp[a][i] += dp[a - coins[i]][i]
return dp[amount][0]
# DYNAMIC PROGRAMMING
# Time: O(n*m)
# Memory: O(n) where n = amount
dp = [0] * (amount + 1)
dp[0] = 1
for i in range(len(coins) - 1, -1, -1):
nextDP = [0] * (amount + 1)
nextDP[0] = 1
for a in range(1, amount + 1):
nextDP[a] = dp[a]
if a - coins[i] >= 0:
nextDP[a] += nextDP[a - coins[i]]
dp = nextDP
return dp[amount]