LeetCode进阶之路(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.

题目:还是寻找路径,不过这次是寻找最短的路径。

思路:还是使用动态规划。

public class Solution {
    public int minPathSum(int[][] grid) {
    if(grid == null || grid.length==0)
        return 0;
 
    int m = grid.length;
    int n = grid[0].length;
 
    int[][] dp = new int[m][n];
    dp[0][0] = grid[0][0];    
 
    // initialize top row
    for(int i=1; i dp[i][j-1]){
                dp[i][j] = dp[i][j-1] + grid[i][j];
            }else{
                dp[i][j] = dp[i-1][j] + grid[i][j];
            }
        }
    }
 
    return dp[m-1][n-1];
}
}

种一棵树最好的时间是十年前,其次是现在!



你可能感兴趣的:(java,leetcode)