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

[leetcode-64-Minimum Path Sum]

时间:2017-03-04 18:47:58      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:span   its   turn   etc   note   申请   cto   point   not   

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.

思路:

很典型的DP问题,如果用grid保存路径和的话

很明显grid[i][j] = grid[i][j] + min(grid[i - 1][j], grid[i][j - 1]);

    int minPathSum2(vector<vector<int>>& grid)
    {
        if (grid.empty())return 0;
        int row = grid.size();
        int col = grid[0].size();
        //其实可以不必申请空间 直接使用grid就行        
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                if (i==0 && j!=0)
                {
                    grid[i][j] += grid[i][j - 1];
                }
                if (i != 0 && j == 0)
                {
                    grid[i][j] += grid[i - 1][j];
                }
                if (i!=0&&j!=0)
                {
                    grid[i][j] = grid[i][j] + min(grid[i - 1][j], grid[i][j - 1]);
                }                
            }
        }
        return grid[row - 1][col - 1];
    }

 

[leetcode-64-Minimum Path Sum]

标签:span   its   turn   etc   note   申请   cto   point   not   

原文地址:http://www.cnblogs.com/hellowooorld/p/6502053.html

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