64. 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.

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

Example:

Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.

Solution

class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] map = new int[m][n];
        if (m == 0 || n == 0) {return 0;}
        map[0][0] = grid[0][0];
        for (int i = 0; i < m; i++){
            for (int j = 0; j < n; j++){
                if (i == 0) {
                    if (j > 0){
                        map[i][j] = grid[i][j] + map[i][j-1];
                    }
                }
                else if (j == 0) {
                    if (i > 0){
                         map[i][j] = grid[i][j] + map[i-1][j];
                    }
                }
                else {
                    map[i][j] = Math.min(map[i-1][j], map[i][j-1]) + grid[i][j];
                }
                
            }
        }
        return map[m-1][n-1];
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容