topic
Given a grid of non-negative integers , find a path from the upper left corner to the lower right corner that minimizes the sum of numbers along the path.m x n
grid
Note: Only move down or right one step at a time.
Example 1:
Input: grid = [[1,3,1],[1,5,1],[4,2,1]] Output: 7 Explanation: Because the sum of the path 1→3→1→1→1 is the smallest.
Example 2:
Input: grid = [[1,2,3],[4,5,6]] Output: 12
hint:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 200
answer
source code
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[][] dp = new int[m][n];
dp[0][0] = grid[0][0];
for (int i = 1; i < m; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
for (int i = 1; i < n; i++) {
dp[0][i] = dp[0][i - 1] + grid[0][i];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
return dp[m - 1][n - 1];
}
}
Summarize
Another dynamic programming, this time I wrote it myself! Use grid[i][j] to represent the minimum path sum from (0,0) to (m,n), equal to the minimum value in dp[i][j - 1] and dp[i - 1][j] plus grid[i][j].