Share my java solution


  • 2
    M
    public int minPathSum(int[][] grid) {
        if(grid==null||grid.length<1)
            return 0;
            
        int[][] minsum = new int[grid.length][grid[0].length];
        //initialize
        minsum[0][0] = grid[0][0];
        
        for(int j=1;j<minsum[0].length;j++){
            minsum[0][j] = minsum[0][j-1]+grid[0][j];
        }
        
        for(int i=1;i<minsum.length;i++){
            minsum[i][0] = minsum[i-1][0] + grid[i][0];
        }
        // calculate sum along the path
        for(int i = 1;i<minsum.length;i++){
            for(int j = 1;j<minsum[0].length;j++){
                minsum[i][j] = Math.min(minsum[i-1][j], minsum[i][j-1]) + grid[i][j];
            }
        }
        
        return minsum[minsum.length-1][minsum[0].length-1];
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.