2014年10月16日星期四

[Leetcode] 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题,没有什么可说的。
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[] dp = new int[n];
        dp[0] = grid[0][0];
        
        for(int i = 1; i < n; i++) {
            dp[i] = dp[i-1] + grid[0][i];
        }
        for(int i = 1; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(j == 0) dp[j] = dp[j] + grid[i][j];
                else {
                    dp[j] = Math.min(dp[j], dp[j-1]) + grid[i][j];
                }
            }
        }
        
        return dp[n-1];
    }

没有评论:

发表评论