Minimum Path Sum(最小路径和)

问题

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.

Notice

You can only move either down or right at any point in time.

Have you met this question in a real interview? Yes
Example

分析

方法和 Unique Paths II(不同的路径 II) 完全一样,大家可以去参阅解析。这里需要提的就是在算当前值的时候要注意条件判断,当在左上角的时候min其实是0,不需要额外添加。当在左边的时候,min是上一个的值。当在上边的时候,min是左边的值。当在其它位置是min是左边和上边的那个小的值。

代码

public class Solution {
    /*
     * @param grid: a list of lists of integers
     * @return: An integer, minimizes the sum of all numbers along its path
     */
    public int minPathSum(int[][] grid) {
        // write your code here
        int m = grid.length;
        int n = grid[0].length;
        int[][] res = new int[2][n];
        int now = 0, last = 0;
        for (int i = 0; i < m; i++) {
            last = now;
            now = 1 - last;
            for (int j = 0; j < n; j++) {
                int min = -1;
                if (i > 0) {
                    min = res[last][j];
                }
                if (j > 0) {
                    if (min > res[now][j - 1] || min == -1) {
                        min = res[now][j - 1];
                    }
                }
                if (min == -1) {
                    min = 0;
                }
                res[now][j] = min + grid[i][j];
            }
        }
        return res[now][n - 1];
    }
}

你可能感兴趣的:(Minimum Path Sum(最小路径和))