LeetCode-Minimum Path Sum[dp]
Minimum Path Sum
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.
分析:
动态规划的经典题目,设dp[i][j]表示从位置[0,0]到[i,j]的最小路径和,要到达位置[i,j]只能从[i,j-1]或[i-1,j]向右或向下走一步到达,
所以状态转移方程为:
dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j];
由二维dp进一步优化为一维dp:
当j=0时,dp[j]=dp[j]+grid[i][j];
当0<j&&j<n时,dp[j]=min(dp[j],dp[j-1])+grid[i][j];
(此时的dp[j]等价于二维dp中的dp[i][j])
参考代码:
public class Solution { public int minPathSum(int[][] grid) { int nlen=grid.length; int mlen=grid[0].length; int dp[]=new int[mlen]; dp[0]=grid[0][0]; for(int j=1;j<mlen;j++){ dp[j]=dp[j-1]+grid[0][j]; } for(int i=1;i<nlen;i++){ for(int j=0;j<mlen;j++){ dp[j]=grid[i][j]+(j==0?(dp[j]):(Math.min(dp[j-1], dp[j]))); } } return dp[mlen-1]; } }