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.
Analysis:
DP problem, use two dimension array
min[i][j] = min(min[i-1][j],min[i][j-1])+A[i][j];
init:
min[0][j] = A[0][j] , min[i][0] = A[i][j]
java
public int minPathSum(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
int [][] min = new int[n][m];
min[0][0] = grid[0][0];
for(int i=1;i<n;i++){
min[i][0] = grid[i][0]+min[i-1][0];
}
for(int i=1;i<m;i++){
min[0][i] = grid[0][i]+min[0][i-1];
}
for(int i=1;i<n;i++){
for(int j=1;j<m;j++){
min[i][j] = Math.min(min[i-1][j], min[i][j-1])+grid[i][j];
}
}
return min[n-1][m-1];
}c++ similar
solution2:
利用滚动数组,更加节俭
java
public int minPathSum(int[][] grid) {
<span style="white-space:pre"> </span>int[] row = new int[grid[0].length];
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(j>0)
row[j]=i>0?Math.min(row[j-1],row[j]):row[j-1];
row[j]+=grid[i][j];
}
}
return row[grid[0].length-1];
}

本文探讨了在一个填充非负数的m x n网格中寻找从左上角到右下角的路径,使得路径上的数字之和最小的问题。采用动态规划方法解决,并提供了两种解决方案:一种使用二维数组存储中间结果;另一种采用滚动数组优化内存使用。
2976

被折叠的 条评论
为什么被折叠?



