/**
* @author realzhaijiayu on 2020/7/23
* @project leetcode
*/
/*
典型的动态规划问题
二维的
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
一维的
dp[j] = min(dp[j], dp[j-1]) + grid[i][j];
*/
//一维的
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
if(m == 0){
return 0;
}
int n = grid[0].length;
int[][] dp = new int[m + 1][n + 1];
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(i == 1){
dp[i][j] = dp[i][j-1] + grid[i-1][j-1];
}
else if(j == 1){
dp[i][j] = dp[i-1][j] + grid[i-1][j-1];
}
else{
dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1]) + grid[i-1][j-1];
}
}
}
return dp[m][n];
}
}
//二维的
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
if(m == 0){
return 0;
}
int n = grid[0].length;
int[] dp = new int[n + 1];
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(i == 1){
dp[j] = dp[j - 1] + grid[i - 1][j - 1];
}
else if(j == 1){
dp[j] = dp[j] + grid[i - 1][j - 1];
}
else{
dp[j] = Math.min(dp[j], dp[j - 1]) + grid[i - 1][j - 1];
}
}
}
return dp[n];
}
}