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

【LeetCode】064. Minimum Path Sum

时间:2017-05-07 22:02:21      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:path   rom   span   time   any   sum   nim   from   otto   

题目:

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 1 ()

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m = (int) grid.size(), n = (int) grid[0].size();
        vector<long> dp(n,INT_MAX);
        dp[0] = grid[0][0];
        for(int i=0; i<m; ++i) {
            for(int j=0; j<n; ++j) {
                if(j > 0)
                    dp[j] = min(dp[j] + grid[i][j], dp[j-1] + grid[i][j]);
                else 
                    if(i>0) dp[j] = dp[j] + grid[i][j];
            }
        }    
        return dp[n-1];
    }
};

  边界的第二种处理方法:因为Solution 1 中dp初始化为最大值,故需要考虑溢出情况,所以用long整型。这个就初始化为int整型。

Solution 2 ()

class Solution {
public:
    int minPathSum(vector<vector<int>>& nums) {
        int m = (int) nums.size();
        int n = (int) nums[0].size();
        vector<int> v (n,0);
        for (int i=0; i<m; ++i) {
            for (int j=0; j<n; ++j) {
                if (i>0)
                    v[j] = nums[i][j] + ((j>0) ? min(v[j], v[j-1]) : v[j]);
                else
                    v[j] = nums[i][j] + ((j>0) ? v[j-1] : 0);
            }
        }
        return v[n-1];
    }
};

  解法没变,就是边界的处理上不一样,这个是先初始化边界了。

Solution 3 ()

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int dp[grid.size()][grid[0].size()];
        
        dp[0][0] = grid[0][0];
        // init first row
        for(int i = 1; i < grid[0].size(); i ++){
            dp[0][i] = dp[0][i-1] + grid[0][i];
        }
        // init first col
        for(int i = 1; i < grid.size(); i ++){
            dp[i][0] = dp[i-1][0] + grid[i][0];
        } 
        for(int i = 1; i < grid.size(); i ++){
            for(int j = 1; j < grid[0].size(); j++){
                dp[i][j] = dp[i - 1][j] < dp[i][j-1]? dp[i - 1][j] + grid[i][j] : dp[i][j-1] + grid[i][j];
            }
        }        
        return dp[grid.size() - 1][grid[0].size() -1];
    }
};

 

【LeetCode】064. Minimum Path Sum

标签:path   rom   span   time   any   sum   nim   from   otto   

原文地址:http://www.cnblogs.com/Atanisi/p/6817097.html

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