标签:
题目:
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.
思路:
设res[i][j]表示从左上角到grid[i][j]的最小路径和。那么res[i][j] = grid[i][j] + min( res[i-1][j], res[i][j-1] );
下面的代码中,为了处理计算第一行和第一列的边界条件,我们令res[i][j]表示从左上角到grid[i-1][j-1]的最小路径和,最后rs[m][n]是我们所求的结果。
/** * @param {number[][]} grid * @return {number} */ var minPathSum = function(grid) { var m=grid.length,n; if(m==0){ return 0; }else{ n=grid[0].length; } var res=[]; for(var i=0;i<m;i++){ for(var j=0;j<n;j++){ res[i]=[]; } } for(var i=0;i<m;i++){ for(var j=0;j<n;j++){ if(i==0&&j==0)res[0][0]=grid[0][0]; else if(j==0)res[i][0]=res[i-1][0]+grid[i][0]; else if(i==0)res[0][j]=res[0][j-1]+grid[0][j]; else res[i][j]=Math.min(res[i-1][j],res[i][j-1])+grid[i][j]; } } return res[m-1][n-1]; };
标签:
原文地址:http://www.cnblogs.com/shytong/p/5115155.html