个人记录-LeetCode 64. Minimum Path Sum

来源:互联网 发布:美国中文导航软件 编辑:程序博客网 时间:2024/05/21 22:44

问题:
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.

问题的思路与Unique Paths和Unique Paths II一致。
唯一不同的是,每个位置保留的结果不再是到达该位置的走法,而是到达该位置最小的sum。

代码示例:

public class Solution {    public int minPathSum(int[][] grid) {        if (grid == null || grid.length < 1 || grid[0].length < 1) {            return 0;        }        int m = grid.length;        int n = grid[0].length;        //初始化        //由于参数数组中也可以含有0,因此边缘初始化为-1        int[][] rst = new int[m+1][n+1];        for (int i = 0; i <= m; ++i) {            rst[i][0] = -1;        }        for (int j = 0; j <= n; ++j) {            rst[0][j]  = -1;        }        for (int i = 1; i <= m; ++i) {            for (int j = 1; j <= n; ++j) {                //第一个位置                if (i == 1 && j == 1) {                    rst[1][1] = grid[0][0];                    continue;                }                //特殊处理第1行和第1列                if (rst[i][j-1] == -1) {                    rst[i][j] = rst[i-1][j] + grid[i-1][j-1];                } else if (rst[i-1][j] == -1){                    rst[i][j] = rst[i][j-1] + grid[i-1][j-1];                } else {                    //其它位置,等于当前位置的值,与min(前一列,上一行)的和                    rst[i][j] = grid[i-1][j-1]                            + (rst[i-1][j] > rst[i][j-1] ? rst[i][j-1] : rst[i-1][j]);                }            }        }        return rst[m][n];    }}
0 0
原创粉丝点击