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.
对m * n 的网格,求其左上角到右下角的最短路径和:
DP问题,计算式是:min(ret[i][j]) = min(ret[i - 1][j], ret[i][j - 1]) + input[i][j];
代码如下:
1 class Solution { 2 public: 3 int minPathSum(vector<vector<int>>& grid) { 4 if(grid.size() == 0 || grid[0].size() == 0) return 0; 5 int szHor = grid.size(); 6 int szVer = grid[0].size(); 7 vector<vector<int>> ret = grid; 8 ret[0][0] = grid[0][0] 9 for(int i = 1; i < szHor; ++i){ 10 ret[i][0] = ret[i - 1][0] + grid[i][0]; 11 } 12 13 for(int i = 1; i < szVer; ++i){ 14 ret[0][i] = ret[0][i - 1] + grid[0][i]; 15 } 16 17 for(int i = 1; i < grid.size(); ++i){ 18 for(int j = 1; j < grid[0].size(); ++j){ 19 ret[i][j] = min(ret[i - 1][j], ret[i][j - 1]) + grid[i][j]; 20 } 21 } 22 return ret[szHor - 1][szVer - 1]; 23 } 24 };
简单的DP问题,java版本代码如下所示:
1 public class Solution { 2 public int minPathSum(int[][] grid) { 3 if(grid.length == 0 || grid[0].length == 0) 4 return 0; 5 int szRol = grid.length; 6 int szCol = grid[0].length; 7 int [][] ret = new int [szRol][szCol]; 8 ret[0][0] = grid[0][0]; 9 for(int i = 1; i < szRol; ++i){ 10 ret[i][0] = ret[i-1][0] + grid[i][0]; 11 } 12 for(int i = 1; i < szCol; ++i){ 13 ret[0][i] = ret[0][i-1] + grid[0][i]; 14 } 15 for(int i = 1; i < szRol; ++i){ 16 for(int j = 1; j < szCol; ++j){ 17 ret[i][j] = Math.min(ret[i-1][j], ret[i][j-1]) + grid[i][j]; 18 } 19 } 20 return ret[szRol-1][szCol-1]; 21 } 22 }