forked from Kyrylo-Ktl/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnique Paths.py
44 lines (32 loc) · 863 Bytes
/
Unique Paths.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
from functools import lru_cache
from math import comb
class Solution:
"""
Time: O(n*m)
Memory: O(n*m)
"""
def uniquePaths(self, n: int, m: int) -> int:
@lru_cache(maxsize=None)
def dp(i: int, j: int) -> int:
if i == 0 or j == 0:
return 1
return dp(i - 1, j) + dp(i, j - 1)
return dp(n - 1, m - 1)
class Solution:
"""
Time: O(n*m)
Memory: O(n*m)
"""
def uniquePaths(self, n: int, m: int) -> int:
dp = [[1] * m for _ in range(n)]
for i in range(1, n):
for j in range(1, m):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[n - 1][m - 1]
class Solution:
"""
Time: O(n+m)
Memory: O(1)
"""
def uniquePaths(self, n: int, m: int) -> int:
return comb(n + m - 2, m - 1)