forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0518-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
classSolution:
defchange(self, amount: int, coins: List[int]) ->int:
# MEMOIZATION
# Time: O(n*m)
# Memory: O(n*m)
cache= {}
defdfs(i, a):
ifa==amount:
return1
ifa>amount:
return0
ifi==len(coins):
return0
if (i, a) incache:
returncache[(i, a)]
cache[(i, a)] =dfs(i, a+coins[i]) +dfs(i+1, a)
returncache[(i, a)]
returndfs(0, 0)
# DYNAMIC PROGRAMMING
# Time: O(n*m)
# Memory: O(n*m)
dp= [[0] * (len(coins) +1) foriinrange(amount+1)]
dp[0] = [1] * (len(coins) +1)
forainrange(1, amount+1):
foriinrange(len(coins) -1, -1, -1):
dp[a][i] =dp[a][i+1]
ifa-coins[i] >=0:
dp[a][i] +=dp[a-coins[i]][i]
returndp[amount][0]
# DYNAMIC PROGRAMMING
# Time: O(n*m)
# Memory: O(n) where n = amount
dp= [0] * (amount+1)
dp[0] =1
foriinrange(len(coins) -1, -1, -1):
nextDP= [0] * (amount+1)
nextDP[0] =1
forainrange(1, amount+1):
nextDP[a] =dp[a]
ifa-coins[i] >=0:
nextDP[a] +=nextDP[a-coins[i]]
dp=nextDP
returndp[amount]