码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Minimum Path Sum

时间:2014-06-28 15:55:58      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:style   blog   java   color   strong      

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

标签:style   blog   java   color   strong      

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!