动态规划的解法
class Solution {
public int minPathSum(int[][] grid) {
if (grid.length == 0 || grid[0].length == 0) {
return 0;
}
// 设f[i][j]为从左上角到坐标(i, j)的最小路径和
// 状态转移方程: f[i][j] = min{ f[i - 1][j], f[i][j - 1] } + grid[i][j]
// 初始条件: f[0][0] = grid[0][0]
// 边界条件:
// 1. f[0][j] = f[0][j - 1] + grid[i][j]
// 2. f[i][0] = f[i - 1][0] + grid[i][j]
int m = grid.length;
int n = grid[0].length;
int f[][] = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
f[i][j] = grid[0][0];
} else if (i == 0) {
f[i][j] = f[i][j - 1] + grid[i][j];
} else if (j == 0) {
f[i][j] = f[i - 1][j] + grid[i][j];
} else {
f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + grid[i][j];
}
}
}
return f[m - 1][n - 1];
}
}
空间压缩
由于第i
行的f[i][j]
只由第i
行和第i - 1
行的数据所决定,所以我们可以进行空间复用,把空间复杂度从O(m * n)
压缩到O(n)
(其中m
是行数,n
是列数)。在动态规划中,压缩行或是列取决于哪个更大。
class Solution {
public int minPathSum(int[][] grid) {
if (grid.length == 0 || grid[0].length == 0) {
return 0;
}
// 设f[i][j]为从左上角到坐标(i, j)的最小路径和
// f[i][j] = min{ f[i - 1][j], f[i][j - 1] } + a[i][j]
int m = grid.length;
int n = grid[0].length;
// 只有两个状态,所以只开两行的空间
int f[][] = new int[2][n];
// 设两个滚动的状态
// old: i - 1
// now: i
int old, now = 0;
for (int i = 0; i < m; i++) {
// 对于每一个新行,交换old和now
old = now;
now = 1 - now;
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
f[now][j] = grid[0][0];
} else if (i == 0) {
f[now][j] = f[now][j - 1] + grid[i][j];
} else if (j == 0) {
f[now][j] = f[old][j] + grid[i][j];
} else {
f[now][j] = Math.min(f[old][j], f[now][j - 1]) + grid[i][j];
}
}
}
return f[now][n - 1];
}
}
如何打印路径
class Solution {
public int minPathSum(int[][] grid) {
if (grid.length == 0 || grid[0].length == 0) {
return 0;
}
final int m = grid.length;
final int n = grid[0].length;
int[][] f = new int[m][n];
// decision[i][j] = 'U':f(i, j)使用的是来自上方的sum
// decision[i][j] = 'L':f(i, j)使用的是来自左方的sum
char[][] decision = new char[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
f[i][j] = grid[0][0];
} else if (i == 0) {
f[i][j] = f[i][j - 1] + grid[i][j];
decision[i][j] = 'L';
} else if (j == 0) {
f[i][j] = f[i - 1][j] + grid[i][j];
decision[i][j] = 'U';
} else {
int t = Math.min(f[i - 1][j], f[i][j - 1]);
f[i][j] = t + grid[i][j];
decision[i][j] = t == f[i - 1][j] ? 'U' : 'L';
}
}
}
// 从左上走到右下有多少步?m + n - 1步
int[] path = new int[m + n - 1];
int i = m - 1;
int j = n - 1;
// 根据决策从最后一步还原到第一步
for (int p = m + n - 2; p >= 0; p--) {
path[p] = grid[i][j];
if (decision[i][j] == 'U') {
i--;
} else if (decision[i][j] == 'L') {
j--;
}
}
// 从第一步打印到最后一步
for (int p = 0; p < m + n - 1; p++) {
System.out.print(path[p] + " ");
}
System.out.println();
return f[m - 1][n - 1];
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] grid = {{1, 5, 7, 6, 8}, {4, 7, 4, 4, 9}, {10, 3, 2, 3, 2}};
System.out.println(solution.minPathSum(grid));
}
}
网友评论