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

Leetcode:Minimum Path Sum 最小路径和

时间:2014-04-28 10:46:41      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:leetcode   动态规划   

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.


此题解法同Triangle 数字三角形。在此不再赘述。

class Solution {
public:
    int minPathSum(vector<vector<int> > &grid) {
        size_t row = grid.size();
        if(row == 0)
            return 0;
        size_t col = grid[0].size();
        
        int **dp = new int *[row];
        for(size_t i = 0; i < row; i++)
        {
            dp[i] = new int[col];
        }
        dp[0][0] = grid[0][0];
        for(size_t i = 1; i < row; i++)
        {
            for(size_t j = 1; j < col; j++)
            {
                dp[i][j] = 0;
            }
        }
        
        for(size_t i = 1; i < col; i++)
            dp[0][i] = dp[0][i - 1] + grid[0][i];
        for(size_t i = 1; i < row; i++)
            dp[i][0] = dp[i - 1][0] + grid[i][0];
            
        for(size_t i = 1; i < row; i++)
            for(size_t j = 1; j < col; j++)
                dp[i][j] = min(dp[i][j - 1],dp[i - 1][j]) + grid[i][j];
        
        int result = dp[row - 1][col - 1];
        
        for(size_t i = 0; i < row; i++)
            delete []dp[i];
        delete []dp;
        
        return result;
    }
};


Leetcode:Minimum Path Sum 最小路径和

标签:leetcode   动态规划   

原文地址:http://blog.csdn.net/u012118523/article/details/24624937

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