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.
二维动态规划
说明
state: dp[x][y]从起点走到x,y的最短路径
function: dp[x][y] = min(dp[x-1][y], dp[x][y-1]) + cost[x][y]
intialize: dp[0][0] = cost[0][0]
// f[i][0] = sum(0,0 -> i,0)
// f[0][i] = sum(0,0 -> 0,i)
answer: f[n-1][m-1]
复杂度
时间O(mn) 空间O(mn)
代码
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];
dp[0][0] = grid[0][0];
for (int i = 1; i < n; i++) {
dp[0][i] = grid[0][i] + dp[0][i - 1];
}
for (int j = 1; j < m; j++) {
dp[j][0] = grid[j][0] + dp[j - 1][0];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
}
return dp[m - 1][n - 1];
}
一维动态规划
说明
初始化第一行的数据, 然后每次遍历一行覆盖一次数据, 思路与二维相同
复杂度
时间O(m*n) 空间O(n)
代码
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[] dp = new int[n];
dp[0] = grid[0][0];
for (int i = 1; i < n; i++) {
dp[i] = dp[i - 1] + grid[0][i];
}
for (int i = 1; i < m; i++) {
for (int j = 0; j < n; j++) {
if (j != 0) {
dp[j] = Math.min(dp[j], dp[j - 1]);
}
dp[j] += grid[i][j];
}
}
return dp[n - 1];
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。