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.
Similar to the unique path problem, it is a DP problem. The solution is to build a new matrix, and each element value is the shortest distance from top left to the point. Recursion can be written based on this, and once the shortest distance to this point is calculated, it is saved for use by other points.
1 public class Solution { 2 public int minPathSum(int[][] grid) { 3 int m = grid.length; 4 int n = grid[0].length; 5 if (m == 0 || n == 0) return 0; 6 int[][] matrix = new int[m][n]; 7 return FindMinPath(m-1, n-1, grid, matrix); 8 } 9 10 public int FindMinPath(int i, int j, int[][]grid, int[][]matrix) {11 if (matrix[i][j] != 0) return matrix[i][j];12 if (i == 0 && j == 0) {13 matrix[i][j] = grid[0][0];14 return matrix[i][j];15 }16 if (i == 0 && j != 0) {17 matrix[i][j] = FindMinPath(i, j-1, grid, matrix) + grid[i][j];18 return matrix[i][j];19 }20 if (i != 0 && j == 0) {21 matrix[i][j] = FindMinPath(i-1, j, grid, matrix) + grid[i][j];22 return matrix[i][j];23 }24 else {25 matrix[i][j] = Math.min(FindMinPath(i, j-1, grid, matrix), FindMinPath(i-1, j, grid, matrix)) + grid[i][j];26 return matrix[i][j];27 }28 }29 }
Leetcode: Minimum path sum