File tree 1 file changed +19
-0
lines changed
1 file changed +19
-0
lines changed Original file line number Diff line number Diff line change @@ -61,6 +61,25 @@ dp[i][j] 表示 到格子 obstacleGrid[i - 1][j - 1] 的所有路径数。
61
61
62
62
由于有障碍物的存在, 因此我们的路径有了限制,具体来说就是:` 如果当前各自是障碍物, 那么 dp[i][j] = 0 ` 。否则 dp[ i] [ j ] = dp[ i - 1] [ j ] + dp[ i] [ j - 1 ]
63
63
64
+ 如果你刚接触动态规划, 西法建议你先写记忆化递归,然后将其转化为标准动态规划。比如本题我们使用记忆化递归解决:
65
+
66
+ ``` py
67
+ class Solution :
68
+ def uniquePathsWithObstacles (self , obstacleGrid : List[List[int ]]) -> int :
69
+ m = len (obstacleGrid)
70
+ if m == 0 : return 0
71
+ n = len (obstacleGrid[0 ])
72
+ @lru_cache (None )
73
+ def dfs (i , j ):
74
+ if i < 0 or i >= m or j < 0 or j >= n: return 0
75
+ if obstacleGrid[i][j] == 1 : return 0
76
+ if i == 0 and j == 0 : return 1
77
+ return dfs(i - 1 , j) + dfs(i, j - 1 )
78
+ return dfs(m - 1 , n - 1 )
79
+ ```
80
+
81
+ > lru_cache(None) 可以看成一个哈希表,key 是函数参数, value 是函数的返回值,因此纯函数都可使用 lru_cache(None) 通过空间换时间的方式来优化性能。
82
+
64
83
代码大概是:
65
84
66
85
Python Code:
You can’t perform that action at this time.
0 commit comments