Leetcode-Minimum Path Sum

LiBlog發表於2014-11-17

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];

相關文章