2014年10月21日星期二

[LeetCode] Minimum Path Sum

Problem:
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.

Solution:

Generally, dynamic programming is applicable to problems exhibiting the properties of overlapping subproblems, and optimal substructure.
For this kind of maximum/minimum problem(also for yes/no, count all possible solutions problems) , when the array cannot be sort or swapped, the solution should be dynamic programming. 

Attention:
Tried to solve the problem by recursion, but failed. Then, tried to use the for-loop, but tried to initialize the two dimensional array form the end to the start, which made it a little bit wired and hard to think.

Code:

public class Solution {
    public int minPathSum(int[][] grid) {
        //state: s[i][j] is minimum path sum from (0,0) to (i,j)
        //function: s[i][j] = min(s[i - 1][j], s[i][j - 1]) + cost[i][j]
        if (grid == null || grid.length == 0) {
            return 0;
        }
        
        int[][] s = new int[grid.length][grid[0].length];
        s[0][0] = grid[0][0];
        
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (i == 0 && j == 0) {
                    continue;
                }
                if (i - 1 < 0) {
                    s[i][j] = s[i][j - 1] + grid[i][j];
                    continue;
                }
                if (j - 1 < 0) {
                    s[i][j] = s[i - 1][j] + grid[i][j];
                    continue;
                }
                s[i][j] = Math.min(s[i - 1][j], s[i][j - 1]) + grid[i][j];
            }
        }
        
        return s[grid.length - 1][grid[0].length - 1];
    }
}

没有评论:

发表评论