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.
public class Solution { //思想与解法同二维dynamic programming的苹果收集问题 public int minPathSum(int[][] grid) { int m = grid.length; // 取得rows int n = grid[0].length; // 取得cols // 状态变量:states[i][j]表示达到点(i-1, j-1)的最小路径和 int states[][] = new int[m][n]; int sum_1 = 0; for (int i = 0; i < n; i++) { //填充状态变量第0行 sum_1 += grid[0][i]; states[0][i] = sum_1; } int sum_2 = 0; for (int j = 0; j < m; j++) { //填充状态变量第0列 sum_2 += grid[j][0]; states[j][0] = sum_2; } if (m < 2 || n < 2) { //避免下面的数组发生(index = -1)溢出 return states[m - 1][n - 1]; } // 状态转移方程:达到点(i,j),要么从上面到达,要么从左面达到 // states[i][j] = min( states[i-1][j]+grid[i][j], states[i][j-1]+grid[i][j] ), { i>=1, j>=1} for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { states[i][j] = Math.min(states[i-1][j] + grid[i][j], states[i][j-1] + grid[i][j]); } } return states[m - 1][n - 1]; } }