Sunday, March 8, 2015

64. Minimum Path Sum Leetcode Java

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.
Solution:
After solving so many similar problems, we know this is dynamic programming problem.
The recursion equation is: 
For first row: res[0][j]=res[0][j-1]+grid[0][j]
For left column: res[i][0]=res[i-1][0]+ grid[i][0]
For all others: res[i][j]=Math.min(res[i-1][j],res[i][j-1])+ grid [i][j]
Time complexity: O(m*n) extra space O(m)
 public int minPathSum(int[][] grid) {  
    if(grid==null || grid.length==0 || grid[0].length==0) return 0;  
    int m=grid.length;  
    int n=grid[0].length;  
    int[] sum=new int[n];  
    for(int i=0;i<m;i++){  
      for(int j=0;j<n;j++){  
        if(j==0) sum[0]+=grid[i][j];  
        else if(i==0) sum[j]=sum[j-1]+grid[i][j];  
        else{  
          sum[j]=grid[i][j]+Math.min(sum[j-1],sum[j]);  
        }  
      }  
    }  
    return sum[n-1];  
   }  

No comments:

Post a Comment