首页 > 其他 > 详细

LeetCode "Minimum Path Sum" - 2D DP

时间:2014-08-03 07:50:54      阅读:433      评论:0      收藏:0      [点我收藏+]

An intuitive 2D DP: dp[i][j] = min(grid[i-1][j-1] + dp[i-1][j], grid[i-1][j-1] + dp[i][j+1])

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

        //    Init
        vector<vector<unsigned long>> dp;
        dp.resize(n + 1); 
        for (int i = 0; i < dp.size(); i++)
            dp[i].resize(m + 1);

        std::fill(dp[0].begin(), dp[0].end(), std::numeric_limits<int>::max());
        for (int i = 0; i <= n; i++) dp[i][0] = std::numeric_limits<int>::max();
        dp[1][1] = grid[0][0];

        for (int i = 1; i <= n; i ++)
        for (int j = 1; j <= m; j++)
        {
            if (i == 1 && j == 1) continue;
            dp[i][j] = std::min(
                grid[i - 1][j - 1] + dp[i - 1][j], 
                grid[i - 1][j - 1] + dp[i][j - 1]
                );
        }

        return dp[n][m];
    }
};

LeetCode "Minimum Path Sum" - 2D DP,布布扣,bubuko.com

LeetCode "Minimum Path Sum" - 2D DP

原文:http://www.cnblogs.com/tonix/p/3888016.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!