LeetCode Minimum Path Sum

来源:互联网 发布:nba数据库统计三分 编辑:程序博客网 时间:2024/06/08 09:07

Minimum Path Sum

 Total Accepted: 18319 Total Submissions: 58624My Submissions

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.

Have you been asked this question in an interview? 


public class Solution {    public int minPathSum(int[][] grid) {        if (grid == null){            return 0;        }        int[][] result = new int[grid.length][grid[0].length];        result[0][0] = grid[0][0];        for (int i = 1; i < grid.length; i++) {            result[i][0] = grid[i][0] + result[i - 1][0];        }        for (int i = 1; i < grid[0].length; i++) {            result[0][i] = grid[0][i] + result[0][i - 1];        }        for (int i = 1; i < grid.length; i++) {            for (int j = 1; j < grid[0].length; j++) {                result[i][j] = Math.min(grid[i][j] + result[i][j - 1], grid[i][j] + result[i - 1][j]);            }        }        return result[grid.length - 1][grid[0].length - 1];    }}


0 0