[leetcode] 64. 最小路径和

64. 最小路径和

63. 不同路径 II 62. 不同路径
思路类似,按题号刷题的强迫症终于尝到了甜头233333

同样使用动态规划

f[i][j]表示,在(i,j)处的最短路径和。由于只能往右走或者往下走,显然,状态转换方程为:

f[i][j] = min(f[i-1][j],f[i][j-1])+g[i][j]

写详细点就是:

if (i == 0 && j == 0) {
                    f[i][j] = grid[0][0];
                } else if (i - 1 < 0) {
                    f[i][j] = f[i][j - 1] + grid[i][j];
                } else if (j - 1 < 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];
                }

代码:

class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        if (m == 0) {
            return 0;
        }
        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 - 1 < 0) {
                    f[i][j] = f[i][j - 1] + grid[i][j];
                } else if (j - 1 < 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];

    }
}
posted @ 2018-07-24 23:16 ACBingo 阅读(...) 评论(...) 编辑 收藏