leetcode -- 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.

[解题思路]

Unique Paths类似,只是把求路径数改成求最小路径和

目标函数:

sum[i][j] = grid[i][j] + Math.min(sum[i+1][j], sum[i][j+1]);

这里为了方便,sum数组分配了[m+2][n+2]个元素,1<=i<=m, 1<=j<=n中存储子问题的解

 1 public int minPathSum(int[][] grid) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         int m = grid.length;
 5         int n = grid[0].length;
 6         int[][] sum = new int[m+2][n+2];
 7         for(int i = 0; i < m + 2; i++){
 8             for(int j = 0; j < n + 2; j++){
 9                 sum[i][j] = Integer.MAX_VALUE;
10             }
11         }
12         sum[m][n+1] = 0;
13         for(int i = m; i >= 1; i--){
14             for(int j = n; j >= 1; j--){
15                 sum[i][j] = grid[i-1][j-1] + Math.min(sum[i+1][j], sum[i][j+1]);
16             }
17         }
18         return sum[1][1];
19     }

 

posted @ 2013-08-20 22:43  feiling  阅读(275)  评论(0编辑  收藏  举报