Leetcode -- Minimum Path Sum

来源:互联网 发布:白兰js 编辑:程序博客网 时间:2024/06/05 00:48

https://leetcode.com/problems/minimum-path-sum/description/

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 Path(http://blog.csdn.net/chaochen1407/article/details/43306873) 和 Unique Path II(http://blog.csdn.net/chaochen1407/article/details/43307579) 的进一步的跟进。原理都是一样的,前两者是f(i, j) = f(i - 1,j) + f(i, j - 1)。这一个就是f(i, j) = min(f(i - 1, j), f(i, j - 1)) + grid(i, j)。 所以具体就不阐述了,看代码吧。


    public int minPathSum(int[][] grid) {        int[] resultRow = new int[grid[0].length];        resultRow[0] = grid[0][0];        for (int i = 0; i < grid.length; i++) {            for (int j = 0; j < grid[0].length; j++) {                if (i == 0 && j == 0) continue;                                int fromLeft = j == 0 ? Integer.MAX_VALUE : resultRow[j - 1];                int fromTop = i == 0 ? Integer.MAX_VALUE : resultRow[j];                resultRow[j] = Math.min(fromLeft, fromTop) + grid[i][j];            }        }                return resultRow[resultRow.length - 1];    }