码迷,mamicode.com
首页 > 其他好文 > 详细

Minimum Path Sum

时间:2015-01-23 17:49:43      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

https://oj.leetcode.com/problems/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[m][n]定义为,到该点的sum。dp[m][n] = min{dp[m - 1][n], dp[m][n - 1]} + grid[m][n]。

public class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        
        int[][] sum = new int[m][n];
        sum[0][0] = grid[0][0];
        for(int i = 1; i < n; i++){
            sum[0][i] = sum[0][i - 1] + grid[0][i];
        }
        
        for(int i = 1; i < m; i++){
            sum[i][0] = sum[i - 1][0] + grid[i][0];
        }
        
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
            }
        }
        return sum[m - 1][n - 1];
    }
}

与上一题一样,仍然可以用一个一维数组定义这个dp,以节省空间。sum[j] = Math.min(sum[j], sum[j - 1]) + grid[i][j];sum永远保存本行的sum[j],所以到点[i][j],前一个点的dp[i - 1][j]已更新,比较他和当前dp[j](未更新,代表上一行)的值,然后再更新当前dp[j]。

public class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        
        int[] sum = new int[n];
        sum[0] = grid[0][0];
        
        for(int i = 1; i < n; i++){
            sum[i] = sum[i - 1] + grid[0][i];
        }
        
        for(int i = 1; i < m; i++){
            for(int j = 0; j < n; j++){
                if(j ==0){
                    sum[j] = sum[j] + grid[i][j];
                }else {
                    sum[j] = Math.min(sum[j], sum[j - 1]) + grid[i][j];
                }
            }
        }
        return sum[n - 1];
    }
}

Minimum Path Sum

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4244432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!