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

LintCode Minimum Path Sum

时间:2016-08-11 12:56:05      阅读:124      评论: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.

 Notice

You can only move either down or right at any point in time!

Dynamic programming is ultilized to solve this problem.

First of all, define another matrix which has same dimension for both x and y. And let us define the number stored in the array stand for the minimum summation of all the path to the position with same x and y in grid matrix. 

Then the sum[i][j] = min(sum[i-1][j],sum[i][j-1]) + grid[i][j];

Initialize the sum[0][0] = grid [0][0]; initialize the two boundaries with all the summation of previous path to that certain node.

Solve sum[m-1][n-1]

 

 1 public class Solution {
 2     /**
 3      * @param grid: a list of lists of integers.
 4      * @return: An integer, minimizes the sum of all numbers along its path
 5      */
 6     public int minPathSum(int[][] grid) {
 7         // write your code here
 8         if (grid == null || grid.length ==0 || grid[0].length == 0) {
 9             return 0;
10         }
11         int m = grid.length;
12         int n = grid[0].length;
13         for(int i = 1; i < m; i++) {
14             grid[i][0] = grid[i-1][0] + grid[i][0];
15         }
16         for(int i = 1; i < n; i++) {
17             grid[0][i] = grid[0][i-1] + grid[0][i];
18         }
19         for(int i= 1; i < m; i ++) {
20             for (int j =1; j < n; j++) {
21                 grid[i][j] = Math.min(grid[i-1][j],grid[i][j-1]) + grid[i][j];
22             }
23         }
24         return grid[m-1][n-1];
25     }
26 }

 

 

LintCode Minimum Path Sum

标签:

原文地址:http://www.cnblogs.com/ly91417/p/5760450.html

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