From 24e7994d2708b90f304dd424f0175bcce845955f Mon Sep 17 00:00:00 2001 From: Jijie LIU Date: Thu, 24 Jun 2021 20:29:02 +0200 Subject: [PATCH] =?UTF-8?q?update=2063.=20=E4=B8=8D=E5=90=8C=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=20II=EF=BC=9A=E6=8F=90=E4=BE=9B=E4=B8=80=E7=BB=B4dp?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84Python=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0063.不同路径II.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 52f00322..a61ffd02 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -232,6 +232,38 @@ class Solution: return dp[-1][-1] ``` +```python +class Solution: + """ + 使用一维dp数组 + """ + + def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: + m, n = len(obstacleGrid), len(obstacleGrid[0]) + + # 初始化dp数组 + # 该数组缓存当前行 + curr = [0] * n + for j in range(n): + if obstacleGrid[0][j] == 1: + break + curr[j] = 1 + + for i in range(1, m): # 从第二行开始 + for j in range(n): # 从第一列开始,因为第一列可能有障碍物 + # 有障碍物处无法通行,状态就设成0 + if obstacleGrid[i][j] == 1: + curr[j] = 0 + elif j > 0: + # 等价于 + # dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + curr[j] = curr[j] + curr[j - 1] + # 隐含的状态更新 + # dp[i][0] = dp[i - 1][0] + + return curr[n - 1] +``` + Go: