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.

 1 class Solution {
 2     public int minPathSum(int[][] grid) {
 3         int m = grid.length;
 4         int n = grid[0].length;
 5         int [][]dp = new int[m + 1][n + 1];
 6         for (int i = 0; i < m; ++i) {
 7             for (int j = 0; j < n; ++j) {
 8                 if (i == 0 && j == 0) {
 9                     dp[i][j] = grid[0][0];
10                     continue;
11                 }
12                 dp[i][j] = -1;
13                 if (i - 1 >= 0) dp[i][j] = dp[i - 1][j] + grid[i][j];
14                 if (j - 1 >= 0 && 
15                     (dp[i][j] == -1 || dp[i][j] > dp[i][j - 1] + grid[i][j])) {
16                         dp[i][j] = dp[i][j - 1] + grid[i][j];
17                     }
18             }
19         }
20         return dp[m - 1][n - 1];
21     }
22                     
23 }
原文地址:https://www.cnblogs.com/hyxsolitude/p/12324112.html