Wednesday, April 27, 2016

[LeetCode] 64. 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.
Subscribe to see which companies asked this question



public class Solution {
    public int minPathSum(int[][] grid) {
        
        int m = grid.length;
        if(0 == m)
            return 0;
        int n = grid[0].length;
        if(0 == n)
            return 0;
            
        int dp[] = new int[m];
        
        dp[0] = grid[0][0];
        for(int i = 1; i < m; ++i){
            dp[i] = dp[i-1] + grid[i][0];
        }
        
        for(int j = 1; j < n; ++j){
            for(int i = 0; i < m; ++i){
                if(0 == i){
                    dp[i] += grid[0][j];
                }
                else{
                    dp[i] = Math.min(dp[i-1], dp[i])+grid[i][j];
                }
            }
        }
        
        return dp[m-1];
        
    }
}

No comments:

Post a Comment