LeetCode 64. Minimum Path Sum

分析

难度 中
来源 https://leetcode.com/problems/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.

解答

Runtime: 2 ms, faster than 99.78% of Java online submissions for Minimum Path Sum.
Memory Usage: 43.6 MB, less than 13.02% of Java online submissions for Minimum Path Sum.

package LeetCode;

public class L64_MinimumPathSum {
    public int minPathSum(int[][] grid) {
        if(grid.length==0||grid[0].length==0)
            return -1;
        int m=grid.length,n=grid[0].length;
        int[][] dp=new int[m][n];//dp[i][j]表示[0][0]到[i][j]之间的距离
        dp[0][0]=grid[0][0];

        //边缘部分初始化
        for(int i=1;i

你可能感兴趣的:(LeetCode,Java)