搜索此博客

2012年8月16日星期四

Minimum Path Sum


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.
This is a typical dynamic programming problem. The  sum value of the current grid is
min(sum at left grid, sum at the up grid) + the value of the current grid. 
01 public int minPathSum(int[][] grid) {      
02   int m=grid.length;  
03   int n=grid[0].length;      
04   if(m<=1&&n<=1)
05     return grid[0][0];
06   int [][]matrix=new int[m][n];
07   matrix[0][0]=grid[0][0];
08 
09   for(int i=1;i<m;i++)
10   {
11     matrix[i][0]=grid[i][0]+matrix[i-1][0];
12   }
13 
14   for(int j=1;j<n;j++)
15   {
16     matrix[0][j]=grid[0][j]+matrix[0][j-1];
17   }
18 
19   for(int i=1;i<m;i++)
20   {
21     for(int j=1;j<n;j++)
22     {
23       matrix[i][j]=findMin(matrix[i-1][j],matrix[i][j-1])+grid[i][j];
24     }
25   }
26 
27   return matrix[m-1][n-1];
28 }
29 
30 public int findMin(int a, int b)
31 {
32   return a<=b?a:b;
33 }

2 条评论:

  1. 赞DP。我一开始也新开了一个matrix计算,后来发现直接在grid上DP就行。不需要额外空间~

    回复删除