美文网首页
LeetCode-Minimum Path Sum

LeetCode-Minimum Path Sum

作者: 圣地亚哥_SVIP | 来源:发表于2018-10-12 17:14 被阅读0次

    题目要求:
    相比较于unique path,寻找一条最短路径,仍然采用动态规划:
    Method: flag[i][j] = grid[i][j]+(flag[i-1][j] < flag[i][j-1]? flag[i-1][j]:flag[i][j-1]);
    源码如下:

    class Solution {
    public:
        void non_uniqpath(vector<vector<int>>& grid,int& num){
            int m = grid.size();
            int n = grid[0].size();
            vector<vector<int>> flag;
            flag.resize(m);
            for_each(flag.begin(),flag.end(),[n](vector<int>& pa){pa.resize(n,0);});
            flag[0][0] = grid[0][0];
            for (int i=1;i<n;i++){
                flag[0][i] = grid[0][i] + flag[0][i-1];
            }
            for (int i=1;i<m;i++){
                flag[i][0] = grid[i][0] + flag[i-1][0];
            }
            for (int i=1;i<m;i++){
                for (int j=1;j<n;++j){
                    flag[i][j] = grid[i][j]+(flag[i-1][j] < flag[i][j-1]? flag[i-1][j]:flag[i][j-1]);
                }
            }
            num = flag[m-1][n-1];
        }
        
        int minPathSum(vector<vector<int>>& grid) {
            int num=0;
            non_uniqpath(grid,num);
            return num;
        }
    };
    

    相关文章

      网友评论

          本文标题:LeetCode-Minimum Path Sum

          本文链接:https://www.haomeiwen.com/subject/zpmgaftx.html