LeetCode题目:Minimum Path Sum

原题地址:https://leetcode.com/problems/minimum-path-sum/

大意:给出一个二维数组(int类型),求出从左上角到右下角最短的路径。

解决方法:动态规划

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        if(!m)
            return 0;
        int n = grid[0].size();

        vector<vector<int>> coll(m, vector<int>(n, 0));
        coll[0][0] = grid[0][0];
        for(int i = 1; i < m; ++i)
            coll[i][0] = grid[i][0] + coll[i - 1][0];
        for(int i = 1; i < n; ++i)
            coll[0][i] = grid[0][i] + coll[0][i - 1];

        for(int i = 1; i < m; ++i)
            for(int j = 1; j < n; ++j)
                coll[i][j] = min(coll[i - 1][j], coll[i][j - 1]) + grid[i][j];

        return coll[m - 1][n - 1];
    }
};

 

posted @ 2016-03-04 17:16  Runnyu  阅读(174)  评论(0编辑  收藏  举报