File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def uniquePaths (self , m : int , n : int ) -> int :
3
+ # Recursive Solution
4
+ # Time: O(2^(m*n))
5
+ # Space: O(m*n)
6
+
7
+ def paths (i , j ):
8
+ if i == j == 0 :
9
+ return 1
10
+ elif i < 0 or j < 0 or i == m or j == n :
11
+ return 0
12
+ else :
13
+ return paths (i - 1 , j ) + paths (i , j - 1 )
14
+
15
+ return paths (m - 1 , n - 1 )
16
+
17
+
18
+
19
+ class Solution :
20
+ def uniquePaths (self , m : int , n : int ) -> int :
21
+ # Top Down DP (Memoization)
22
+ # Time: O(m*n)
23
+ # Space: O(m*n)
24
+
25
+ memo = {(0 ,0 ): 1 }
26
+ def paths (i , j ):
27
+ if (i ,j ) in memo :
28
+ return memo [(i ,j )]
29
+ elif i < 0 or j < 0 or i == m or j == n :
30
+ return 0
31
+ else :
32
+ val = paths (i , j - 1 ) + paths (i - 1 , j )
33
+ memo [(i ,j )] = val
34
+ return val
35
+
36
+ return paths (m - 1 , n - 1 )
37
+
38
+
39
+
40
+ class Solution :
41
+ def uniquePaths (self , m : int , n : int ) -> int :
42
+ # Bottom Up DP (Tabulation)
43
+ # Time: O(m*n)
44
+ # Space: O(m*n)
45
+
46
+ dp = []
47
+ for _ in range (m ):
48
+ dp .append ([0 ] * n )
49
+
50
+ dp [0 ][0 ] = 1
51
+
52
+ for i in range (m ):
53
+ for j in range (n ):
54
+ if i == j == 0 :
55
+ continue
56
+
57
+ val = 0
58
+ if i > 0 :
59
+ val += dp [i - 1 ][j ]
60
+ if j > 0 :
61
+ val += dp [i ][j - 1 ]
62
+
63
+ dp [i ][j ] = val
64
+
65
+ return dp [m - 1 ][n - 1 ]
66
+
You can’t perform that action at this time.
0 commit comments