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.
Note: You can only move either down or right at any point in time.
分析:
看到最优化,想到动态规划。
子问题:
从左上角到位置(i,j)最小路径和,设为dp[i][j].
因为有两种转移方式,往下或往右,所以结果是这两种转移方式取最小:
dp[i][j] = min{ dp[i-1][j], dp[i][j-1]} + grid[]i[j]
如果用二维字典,就这样了。
可以用一维字典,记录当前行的最优值即可。
public class Solution {
public int minPathSum(int[][] grid) {
if(grid==null || grid.length==0 || grid[0].length==0)
return 0;
int row = grid.length;
int col = grid[0].length;
int[] dp = new int[col];
//除了第一个,其余最大整数,方便后面min
for(int i=1; i<col; i++)
dp[i] = Integer.MAX_VALUE;
for(int i=0; i<row; i++){
//第一个只有一路往下加起立
dp[0] = dp[0] + grid[i][0];
for(int j=1; j<col; j++)
//后面的dp[j]记录的实际上是上一行此位置的最优值
dp[j] = Math.min( dp[j-1], dp[j]) + grid[i][j];
}
return dp[col-1];
}
}