标签:style blog http color io 使用 ar div 问题
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.
与Unique Path问题相似,是一个DP问题,解决问题的方案依然是建造一个新矩阵,每个元素值是从top left到该点的最短距离。递归式可以根据这个写出来,并且一旦计算出了到该点的最短距离,就把它存起来以备其他点使用。
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 }
标签:style blog http color io 使用 ar div 问题
原文地址:http://www.cnblogs.com/EdwardLiu/p/3958961.html