Wednesday, July 16, 2014

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.

DP: 用一个二维数组,map[i][j] = Math.min(map[i - 1][j] + grid[i][j], map[i][j - 1] + grid[i][j]),我们可以只用一维数组来代替。
public class Solution {
    //Time: O(m*n)  Space: O(n)
    public int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        
        int[] map = new int[grid[0].length];
        map[0] = grid[0][0];
        for (int i = 1; i < map.length; i++) {
            map[i] = map[i - 1] + grid[0][i];
        }
        for (int i = 1; i < grid.length; i++) {
            map[0] += grid[i][0];
            for (int j = 1; j < grid[0].length; j++) {
                map[j] = Math.min(map[j - 1] + grid[i][j], map[j] + grid[i][j]);
            }
        }
        return map[map.length - 1];
    }
}

No comments:

Post a Comment