-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathUniquePathsTopDownDP.py
More file actions
51 lines (34 loc) · 816 Bytes
/
UniquePathsTopDownDP.py
File metadata and controls
51 lines (34 loc) · 816 Bytes
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
50
# Example 1:
# Input: m = 3, n = 2
# Output: 3
# Explanation:
# From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
# 1. Right -> Right -> Down
# 2. Right -> Down -> Right
# 3. Down -> Right -> Right
# Example 2:
# Input: m = 7, n = 3
# Output: 28
# [
# [1, 1, 1],
# [1, 2, 3],
# ]
def unique_paths_rec(m, n, i, j, memo):
if m - 1 == i and n - 1 == j:
return 1
elif i >= m or j >= n:
return 0
key = str(i) + "," + str(j)
if key in memo:
return memo[key]
num_paths = unique_paths_rec(m, n, i + 1, j, memo) + unique_paths_rec(m, n, i, j + 1, memo)
memo[key] = num_paths
return num_paths
def unique_paths(m, n):
return unique_paths_rec(m, n, 0, 0, dict())
print(unique_paths(3, 2))
print(unique_paths(7, 3))
print(unique_paths(15, 15))
3
28
40116600