2014年2月11日星期二

LeetCoder - 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.

public class Solution {
    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 max[][] = new int[m][n];
        for(int i=0;i<m;i++) {
            for(int j=0;j<n;j++) {
                if(i==0 && j==0) {
                    max[0][0] = grid[0][0];
                } else if(i==0 && j!=0) {
                    max[i][j] = max[i][j-1] + grid[i][j];
                } else if(i!=0 && j==0) {
                    max[i][j] = max[i-1][j] + grid[i][j];
                } else {
                    max[i][j] = Math.min(max[i][j-1] + grid[i][j], max[i-1][j]+grid[i][j]);
                }
            }
        }
        return max[m-1][n-1];
    }
}

========

public class Solution {
    public int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int row = grid.length;
        int column = grid[0].length;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                if (i == 0 && j == 0) {
                    grid[i][j] = grid[i][j];
                } else if (i == 0) {
                    grid[i][j] = grid[i][j] + grid[i][j - 1];
                } else if (j == 0) {
                    grid[i][j] = grid[i][j] + grid[i - 1][j];
                } else {
                    grid[i][j] = Math.min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j];
                }
            }
        }
        return grid[row - 1][column - 1];
    }
}

没有评论:

发表评论