题目:
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 Path系列是思路一样的。具体思路看代码就很清楚了
代码如下:
1
public
int minPathSum(
int[][] grid) {
2 int m = grid.length;
3 int n = grid[0].length;
4
5 if(m==0||n==0)
6 return 0;
7
8 int[][] dp = new int[m][n];
9
10 dp[0][0]=grid[0][0];
11
12 // a row
13 for ( int i = 1; i < n; i++)
14 dp[0][i] = dp[0][i - 1] + grid[0][i];
15
16 // a column
17 for ( int j = 1; j < m; j++)
18 dp[j][0] = dp[j - 1][0] + grid[j][0];
19
20 for ( int i=1; i<m; i++){
21 for ( int j=1; j<n; j++){
22 if(dp[i-1][j]<dp[i][j-1])
23 dp[i][j]=dp[i-1][j]+grid[i][j];
24 else
25 dp[i][j]=dp[i][j-1]+grid[i][j];
26 }
27 }
28 return dp[m-1][n-1];
29 }
2 int m = grid.length;
3 int n = grid[0].length;
4
5 if(m==0||n==0)
6 return 0;
7
8 int[][] dp = new int[m][n];
9
10 dp[0][0]=grid[0][0];
11
12 // a row
13 for ( int i = 1; i < n; i++)
14 dp[0][i] = dp[0][i - 1] + grid[0][i];
15
16 // a column
17 for ( int j = 1; j < m; j++)
18 dp[j][0] = dp[j - 1][0] + grid[j][0];
19
20 for ( int i=1; i<m; i++){
21 for ( int j=1; j<n; j++){
22 if(dp[i-1][j]<dp[i][j-1])
23 dp[i][j]=dp[i-1][j]+grid[i][j];
24 else
25 dp[i][j]=dp[i][j-1]+grid[i][j];
26 }
27 }
28 return dp[m-1][n-1];
29 }