您的位置:首页 > 其它

LeetCode Minimum Path Sum

2014-10-18 19:23 260 查看
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.

public class Solution {
public int minPathSum(int[][] grid) {
if (grid==null) {
return 0;
}
int minpath=0;
int m=grid.length;
int n=grid[0].length;
int[][] sumpath=new int[m]
;
sumpath[0][0]=grid[0][0];
for (int j = 1; j < n; j++) {
sumpath[0][j]=sumpath[0][j-1]+grid[0][j];
}

for (int i = 1; i < m; i++) {
sumpath[i][0]=sumpath[i-1][0]+grid[i][0];
}

for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
sumpath[i][j]=grid[i][j]+Math.min(sumpath[i][j-1], sumpath[i-1][j]);
}
}

return sumpath[m-1][n-1];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: