Skip to content

Commit

Permalink
Update 63.unique-paths-ii.md
Browse files Browse the repository at this point in the history
  • Loading branch information
azl397985856 authored Oct 16, 2020
1 parent 386be21 commit 68b70da
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions problems/63.unique-paths-ii.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,25 @@ dp[i][j] 表示 到格子 obstacleGrid[i - 1][j - 1] 的所有路径数。

由于有障碍物的存在, 因此我们的路径有了限制,具体来说就是:`如果当前各自是障碍物, 那么 dp[i][j] = 0`。否则 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

如果你刚接触动态规划, 西法建议你先写记忆化递归,然后将其转化为标准动态规划。比如本题我们使用记忆化递归解决:

```py
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid)
if m == 0: return 0
n = len(obstacleGrid[0])
@lru_cache(None)
def dfs(i, j):
if i < 0 or i >= m or j < 0 or j >= n: return 0
if obstacleGrid[i][j] == 1: return 0
if i == 0 and j == 0: return 1
return dfs(i - 1, j) + dfs(i, j - 1)
return dfs(m - 1, n - 1)
```

> lru_cache(None) 可以看成一个哈希表,key 是函数参数, value 是函数的返回值,因此纯函数都可使用 lru_cache(None) 通过空间换时间的方式来优化性能。
代码大概是:

Python Code:
Expand Down

0 comments on commit 68b70da

Please sign in to comment.