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

LeetCode "Minimum Path Sum" - 2D DP

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

标签:style   blog   color   io   for   div   amp   size   

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

标签:style   blog   color   io   for   div   amp   size   

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

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