leetcode 64. 最小路径和

题解

动态规划问题,grid[i][j] += min(grid[i-1][j], grid[i][j-1])

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
func minPathSum(grid [][]int) int {
m := len(grid)
if m == 0 {
return 0
}
n := len(grid[0])
if n == 0 {
return 0
}
for i := 1; i < n; i++ {
grid[0][i] += grid[0][i-1]
}
for i := 1; i < m; i++ {
grid[i][0] += grid[i-1][0]
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] += min(grid[i-1][j], grid[i][j-1])
}
}
return grid[m-1][n-1]
}

func min(a, b int) int {
if a <= b {
return a
}
return b
}