Skip to content

Commit bdb0ccc

Browse files
committed
add: 62
1 parent 25b840f commit bdb0ccc

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
| # | Title | Level | Time | Space | Tags | Note |
88
| ---- | -------------------------------------------------------------------------------------------------------------------------- | ------ | ------------ | ---------- | ------------------------------------------------------------------- | ----------------------------- |
99
| 57 | [Insert Interval](./src/57.insert-interval.py) | Medium | O(N) | O(N) | Array, Matrix, Dynamic Programming | DP (Merging Intervals) |
10+
| 62 | [Unique Paths](./src/62.unique-paths.py) | Medium | O(M\*N) | O(M\*N) | Array, Matrix, Dynamic Programming | DP (Distinct Ways) |
1011
| 64 | [Minimum Path Sum](./src/64.minimum-path-sum.py) | Medium | O(N\*M) | O(N\*M) | Array, Matrix, Dynamic Programming | DP (Min - Max) |
1112
| 70 | [Climbing Stairs](./src/70.climbing-stairs.py) | Easy | O(N) | O(N) | Dynamic Programming | DP (Min - Max) |
1213
| 120 | [Triangle](./src/120.triangle.py) | Medium | O(N^2) | O(N^2) | Array, Dynamic Programming | DP (Min - Max) |

src/62.unique-paths.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Level: Medium
2+
# TAGS: Math, Dynamic Programming, Combinatorics
3+
4+
5+
class Solution:
6+
"""
7+
DP Top-Down | Time and Space: O(M*N)
8+
"""
9+
10+
def uniquePaths(self, m: int, n: int) -> int:
11+
memo = {}
12+
13+
def dfs(i, j):
14+
if i < 0 or j < 0:
15+
return 0
16+
if i == 0 and j == 0:
17+
return 1
18+
19+
if (i, j) in memo:
20+
return memo[(i, j)]
21+
22+
memo[(i, j)] = dfs(i - 1, j) + dfs(i, j - 1)
23+
return memo[(i, j)]
24+
25+
return dfs(m - 1, n - 1)
26+
27+
"""
28+
DP Bottom-Up
29+
"""
30+
31+
def uniquePaths1(self, m: int, n: int) -> int:
32+
dp = [[1] * n for i in range(m)]
33+
for i in range(1, m):
34+
for j in range(1, n):
35+
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
36+
return dp[-1][-1]
37+
38+
39+
tests = [
40+
(
41+
(
42+
3,
43+
7,
44+
),
45+
28,
46+
),
47+
(
48+
(
49+
3,
50+
2,
51+
),
52+
3,
53+
),
54+
]

0 commit comments

Comments
 (0)