Skip to content

Commit 1b921c0

Browse files
committed
feat: unique-paths-ii
1 parent cb162c8 commit 1b921c0

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

dy.unique-paths-ii.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
63. 不同路径 II
6+
https://leetcode-cn.com/problems/unique-paths-ii/
7+
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
8+
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
9+
现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
10+
"""
11+
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
12+
m = len(obstacleGrid)
13+
n = len(obstacleGrid[0])
14+
res = [[0] * n for _ in range(m)]
15+
for i in range(m):
16+
for j in range(n):
17+
if not obstacleGrid[i][j]:
18+
if i == j == 0:
19+
res[i][j] = 1
20+
else:
21+
a = res[i-1][j] if i != 0 else 0
22+
b = res[i][j-1] if j != 0 else 0
23+
res[i][j] = a + b
24+
25+
return res[-1][-1]
26+
27+
28+
so = Solution()
29+
print(so.uniquePathsWithObstacles([[0,0,0],[0,1,0],[0,0,0]]))

dy.unique-paths.py

+8
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@ class Solution:
77
问总共有多少条不同的路径?
88
"""
99
def uniquePaths(self, m: int, n: int) -> int:
10+
cur = [1] * n
11+
for i in range(1, m):
12+
for j in range(1, n):
13+
cur[j] += cur[j - 1]
14+
print('curr', i + 1, j + 1, cur[j-1], cur[j])
15+
return cur[-1]
16+
17+
def uniquePathsByArr(self, m: int, n: int) -> int:
1018
# 生成缓存数组
1119
dp = [[1] * n] + [[1] + [0] * (n - 1) for _ in range(m - 1)]
1220
print(dp)

0 commit comments

Comments
 (0)