Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1eb7430

Browse files
🐱(dynamic): 64. 最小路径和
1 parent 2aa99c4 commit 1eb7430

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎docs/algorithm/dynamic/README.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,48 @@ class Solution(object):
276276
- 时间复杂度:`O(m*n)`
277277
- 空间复杂度:`O(2n)`
278278

279+
## 64. 最小路径和
280+
281+
[原题链接](https://leetcode-cn.com/problems/minimum-path-sum/)
282+
283+
### 思路
284+
285+
动态规划。
286+
287+
只能通过该点的左边或是上边到达某个点,因此 `dp[x][y] = min(dp[x - 1][y], dp[x][y - 1]) + grid[x][y]`
288+
289+
注意边界处理。
290+
291+
```python
292+
class Solution:
293+
def minPathSum(self, grid: List[List[int]]) -> int:
294+
m = len(grid)
295+
if m == 0:
296+
return 0
297+
n = len(grid[0])
298+
299+
dp = [[0 for _ in range(n)] for _ in range(m)]
300+
301+
for i in range(m):
302+
for j in range(n):
303+
if i == 0 and j == 0:
304+
dp[i][j] = grid[i][j]
305+
continue
306+
307+
if i == 0:
308+
dp[i][j] = dp[i][j-1] + grid[i][j]
309+
elif j == 0:
310+
dp[i][j] = dp[i-1][j] + grid[i][j]
311+
else:
312+
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
313+
314+
return dp[m-1][n-1]
315+
```
316+
317+
### 复杂度
318+
319+
- 时间复杂度 `O(m*n)`
320+
- 空间复杂度:`O(m*n)`(如果复用 `grid` 的话也可以达到 `O(1)`)
279321

280322
## 70. 爬楼梯
281323

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /