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

Leetcode-Minimum Path Sum

时间:2014-11-17 01:39:53      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   sp   for   strong   div   

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.

Analysis:

This is a DP problem. d[i][j] is the min path sum from src to grid[i][j].

d[i][j] = min{d[i-1][j],d[i][j-1]}+grid[i][j];

Solution:

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

NOTE: We can reduce the memory space to O(n) by using just on array. The formula:

d[i] = min{d[i],d[i-1]}+grid[i][j];

Leetcode-Minimum Path Sum

标签:style   blog   io   color   ar   sp   for   strong   div   

原文地址:http://www.cnblogs.com/lishiblog/p/4102738.html

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