标签:mini path 最小 project code 规划 etc 动态规划 动态
/**
* @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];
}
}
标签:mini path 最小 project code 规划 etc 动态规划 动态
原文地址:https://www.cnblogs.com/realzhaijiayu/p/13368803.html