-
Difficulty: Medium
-
Related Topics: Array, Dynamic Programming
Description
Given a m x n
grid
filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
给定一个 m x n
的矩阵,矩阵元素都是非负书,寻找一条从左上角到右下角的路径,使得路径上的数的和最小。
Note
You can only move either down or right at any point in time.
Examples
Example 1
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Example 2
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Constraints
-
m == grid.length
-
n == grid[i].length
-
1 <= m, n <= 200
-
0 <= grid[i][j] <= 100
Solution
动态规划其中一道例题,状态方程如下:
[ exttt{dp(i, j)} = egin{cases}
exttt{dp(i - 1, j)} + exttt{grid[i][j]}, & j = 0 \
exttt{dp(i, j - 1)} + exttt{grid[i][j]}, & i = 0 \
exttt{dp(i - 1, j - 1)} + min( exttt{grid[i - 1][j]}, exttt{grid[i][j - 1]}), & else
end{cases}
]
其中 dp(i, j)
表示到 (i, j)
位置时的最短路径
import kotlin.math.min
class Solution {
fun minPathSum(grid: Array<IntArray>): Int {
val dp = Array(grid.size) { IntArray(grid[0].size) }
dp[0][0] = grid[0][0]
for (i in 1..grid.lastIndex) {
dp[i][0] = dp[i - 1][0] + grid[i][0]
}
for (i in 1..grid[0].lastIndex) {
dp[0][i] = dp[0][i - 1] + grid[0][i]
}
for (i in 1..grid.lastIndex) {
for (j in 1..grid[i].lastIndex) {
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])
}
}
return dp.last().last()
}
}