Question:
Given an mxn grid containing non-negative integers, find a path from the upper left corner to the lower right corner such that the sum of the numbers on the path is the smallest.
Description: A robot can 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 minimum.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Analysis:
The idea of this question is similar to that of Question 98, so I won't repeat the details. It can be easily solved by finding the state transition equation question.
The state transition equation f(i,j) is equal to the minimum of f(i-1,j) and f(i,j-1) plus grid[i][j].
Code:
public class MinPathSum {
public static void main(String[] args) {
int[][] grid = {
{
1,3,1},{
1,5,1}};
System.out.println(grid.length);
System.out.println(grid[0].length);
}
public int minPathSum1(int[][] grid) {
int[][] dp = new int[grid.length][grid[0].length];
dp[0][0] = grid[0][0];
for (int j = 1; j < grid[0].length; j++) {
dp[0][j] = dp[0][j-1] + grid[0][j];
}
for (int i = 1; i < grid.length; i++) {
dp[i][0] = dp[i-1][0] + grid[i][0];
for (int j = 1; j < grid[0].length; j++) {
int prev = Math.min(dp[i][j-1],dp[i-1][j]);
dp[i][j] = grid[i][j]+prev;
}
}
return grid[grid.length-1][grid[0].length-1];
}
// 优化空间效率,只需要一个一维数组dp
public int minPathSum3(int[][] grid){
int[] dp = new int[grid[0].length];
dp[0] = grid[0][0];
for (int j = 1; j < grid[0].length; j++) {
dp[j] = dp[j-1] + grid[0][j];
}
for (int i = 1; i < grid.length; i++) {
dp[0] += grid[i][0];
for (int j = 1; j < grid[0].length; j++) {
dp[j] = Math.min(dp[j-1],dp[j])+grid[i][j];
}
}
return dp[grid[0].length-1];
}
}