LeetCode Solutions : 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.

Java Solutions:

1. DP, O(n^2) time, O(n^2) space

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

2.DP, O(n^2) time, O(n) space

public class Solution {
    public int minPathSum(int[][] grid) {
        if(grid==null||grid.length==0)
			return 0;
		int row=grid.length;
		int column=grid[0].length;
		int[] results=new int[column];
		//init
		Arrays.fill(results,Integer.MAX_VALUE);
		results[0]=0;
		for(int i=0;i<row;i++){
			//init the 0th sum = old 0th element + the new 0th element
			//just init the 0th column every time dynamically			
			results[0]=grid[i][0]+results[0];
			//// loop through each element of each row
			for(int j=1;j<column;j++){
				results[j]=grid[i][j]+Math.min(results[j],results[j-1];
			}
		}
		return results[column-1];
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章