首页 > 其他 > 详细

【leetcode】Minimum Path Sum

时间:2014-06-28 15:53:44      阅读:355      评论:0      收藏:0      [点我收藏+]

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 Paths这道题,只是初始化和更新answer数组的方式不同。

代码如下(Java):

 1 public class Solution {
 2     public int minPathSum(int[][] grid) {
 3         int m = grid.length;
 4         int n = grid[0].length;
 5         int[][] answer = new int[m][n];
 6         
 7         answer[0][0] = grid[0][0];
 8         for(int i = 1;i < m;i++)
 9             answer[i][0] = answer[i-1][0] + grid[i][0];
10         for(int i = 1;i < n;i++)
11             answer[0][i] = answer[0][i-1] + grid[0][i];
12         
13         
14         for(int i = 1;i < m;i++)
15         {
16             for(int j = 1;j < n;j++){
17                 answer[i][j] = Math.min(answer[i-1][j],answer[i][j-1])+grid[i][j] ;
18             }
19         }
20         
21         return answer[m-1][n-1];
22     }
23 }

 

 

【leetcode】Minimum Path Sum,布布扣,bubuko.com

【leetcode】Minimum Path Sum

原文:http://www.cnblogs.com/sunshineatnoon/p/3798193.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!