File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def change (self , amount : int , coins : List [int ]) -> int :
3
+ # MEMOIZATION
4
+ # Time: O(n*m)
5
+ # Memory: O(n*m)
6
+ cache = {}
7
+
8
+ def dfs (i , a ):
9
+ if a == amount :
10
+ return 1
11
+ if a > amount :
12
+ return 0
13
+ if i == len (coins ):
14
+ return 0
15
+ if (i , a ) in cache :
16
+ return cache [(i , a )]
17
+
18
+ cache [(i , a )] = dfs (i , a + coins [i ]) + dfs (i + 1 , a )
19
+ return cache [(i , a )]
20
+
21
+ return dfs (0 , 0 )
22
+
23
+
24
+ # DYNAMIC PROGRAMMING
25
+ # Time: O(n*m)
26
+ # Memory: O(n*m)
27
+ dp = [[0 ] * (len (coins ) + 1 ) for i in range (amount + 1 )]
28
+ dp [0 ] = [1 ] * (len (coins ) + 1 )
29
+ for a in range (1 , amount + 1 ):
30
+ for i in range (len (coins ) - 1 , - 1 , - 1 ):
31
+ dp [a ][i ] = dp [a ][i + 1 ]
32
+ if a - coins [i ] >= 0 :
33
+ dp [a ][i ] += dp [a - coins [i ]][i ]
34
+ return dp [amount ][0 ]
35
+
36
+
37
+ # DYNAMIC PROGRAMMING
38
+ # Time: O(n*m)
39
+ # Memory: O(n) where n = amount
40
+ dp = [0 ] * (amount + 1 )
41
+ dp [0 ] = 1
42
+ for i in range (len (coins ) - 1 , - 1 , - 1 ):
43
+ nextDP = [0 ] * (amount + 1 )
44
+ nextDP [0 ] = 1
45
+
46
+ for a in range (1 , amount + 1 ):
47
+ nextDP [a ] = dp [a ]
48
+ if a - coins [i ] >= 0 :
49
+ nextDP [a ] += nextDP [a - coins [i ]]
50
+ dp = nextDP
51
+ return dp [amount ]
You can’t perform that action at this time.
0 commit comments