LeetCode 64 最小路径和
Leetcode 64 最小路径和
典型的动态规划问题
/**动态规划
* 1. DP[i][j]表示从起点(0,0)到(i,j)位置的最小路径
* 2. DP[i][j]只与DP[i-1][j]、DP[i][j-1]有关
* 3. DP[i][j] = Min(DP[i-1][j], DP[i][j-1]) + grid[i][j]
*/
/*第一种: 二维DP数组*/
//用二维数组存储grid中每一个位置上的DP值
class Solution {
public int minPathSum(int[][] grid) {
if(grid==null || grid.length==0 || grid[0].length==0) return 0;
int[][] dp = new int[grid.length][grid[0].length];
/*状态递推: 按行*/
for(int i=0; i<grid.length; i++){
for(int j=0; j<grid[0].length; j++){
if(i==0 && j==0) dp[i][j] = grid[i][j];
else if(i==0)
dp[i][j] = dp[i][j-1] + grid[i][j];
else if(j==0)
dp[i][j] = dp[i-1][j] + grid[i][j];
else
dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j]) + grid[i][j];
}
}
return dp[grid.length-1][grid[0].length-1];
}
}
/*第二种: 一维DP数组*/
//用一维数组每次存储上一行的DP结果,则下一行DP结果直接在原数组基础上存储
class Solution {
public int minPathSum(int[][] grid) {
if(grid==null || grid.length==0 || grid[0].length==0) return 0;
int[] dp = new int[grid[0].length];
/*状态递推: 按行*/
for(int i=0; i<grid.length; i++){
for(int j=0; j<grid[0].length; j++){
if(i==0 && j==0) dp[j] = grid[i][j];
else if(i==0)
dp[j] = dp[j-1] + grid[i][j];
else if(j==0)
dp[j] = dp[j] + grid[i][j];
else
dp[j] = Math.min(dp[j-1], dp[j]) + grid[i][j];
}
}
return dp[grid[0].length-1];
}
}
/*第三种: 无需额外空间*/
class Solution {
public int minPathSum(int[][] grid) {
if(grid==null || grid.length==0 || grid[0].length==0) return 0;
/*状态递推: 按行*/
for(int i=0; i<grid.length; i++){
for(int j=0; j<grid[0].length; j++){
if(i==0 && j==0) continue;
else if(i==0)
grid[i][j] = grid[i][j-1] + grid[i][j];
else if(j==0)
grid[i][j] = grid[i-1][j] + grid[i][j];
else
grid[i][j] = Math.min(grid[i][j-1], grid[i-1][j]) + grid[i][j];
}
}
return grid[grid.length-1][grid[0].length-1];
}
}