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.

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

 

posted @ 2014-02-07 03:52  krunning  阅读(140)  评论(0编辑  收藏  举报