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.

LeetCode: Minimum Path Sum 解题报告

SOLUTION 1:

相当基础的DP题目:

This is a simple DP.
表达式:  D[i][j]: 从左下到本点的最小值
递推公式: D[i][j] = Math.mn(D[i - 1][j], D[i][j - 1]) + grid[i][j]
初始化:  D[i][j] = grid[i][j].

终止条件:到达终点

 1 // Solution 1: DP
 2     public int minPathSum1(int[][] grid) {
 3         if (grid == null || grid.length == 0 || grid[0].length == 0) {
 4             return 0;
 5         }
 6         
 7         int rows = grid.length;
 8         int cols = grid[0].length;
 9         int[][] D = new int[rows][cols];
10         
11         // This is a simple DP.
12         // 表达式:  D[i][j]: 从左下到本点的最小值
13         // 递推公式: D[i][j] = Math.mn(D[i - 1][j], D[i][j - 1]) + grid[i][j]
14         // 初始化:  D[i][j] = grid[i][j].
15         for (int i = 0; i < rows; i++) {
16             for (int j = 0; j < cols; j++) {
17                 D[i][j] = grid[i][j];
18                 
19                 if (i == 0 && j != 0) {
20                     D[i][j] += D[i][j - 1];
21                 } else if (j == 0 && i != 0) {
22                     D[i][j] += D[i - 1][j];
23                 } else if (i != 0 && j != 0) {
24                     D[i][j] += Math.min(D[i][j - 1], D[i - 1][j]);
25                 }
26             }
27         }
28         
29         return D[rows - 1][cols - 1];
30     }
View Code

相关文章: