64. Minimum Path Sum
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.
Example:
Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
题意:给一个二维数组,从左上至右下,求出经过项的和最小
代码如下:
/** * @param {number[][]} grid * @return {number} */ //让每项和它的左边和上边比较 var minPathSum = function(grid) { var rowLen=grid.length; var colLen=grid[0].length; var res=[]; for(var i=0;i<rowLen;i++){ res[i]=new Array(); for(var j=0;j<colLen;j++){ res[i][j]=0; } } res[0][0]=grid[0][0]; //第一行 for(var i=1;i<colLen;i++){ res[0][i]=res[0][i-1]+grid[0][i]; } //第一列 for(var i=1;i<rowLen;i++){ res[i][0]=res[i-1][0]+grid[i][0]; } //其他 for(var i=1;i<rowLen;i++){ for(var j=1;j<colLen;j++){ res[i][j]=grid[i][j]+Math.min(res[i][j-1],res[i-1][j]); } } return res[i-1][j-1]; };