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.

similar to 62 Unique Path

public class Solution {
    public int minPathSum(int[][] grid) {
        if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;

        int[][] sum = new int[grid.length][grid[0].length];

        sum[0][0] = grid[0][0];

        for(int i=1; i< grid.length; i++){
            sum[i][0] = sum[i-1][0] + grid[i][0];
        }
        for(int j=1; j<grid[0].length; j++){
            sum[0][j] = sum[0][j-1] + grid[0][j];
        }

        for(int i=1; i<grid.length; i++){
            for(int j=1; j<grid[0].length; j++){
                sum[i][j] = Math.min(sum[i-1][j], sum[i][j-1]) + grid[i][j];
            } 
        }
        return sum[grid.length-1][grid[0].length-1];
    }
}

you can also improve this by using only one array, which sum[j-1] is current line's result. corresponding to sum[i][j-1], and sum[j] is sum[i-1][j];

results matching ""

    No results matching ""