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

[leetcode]Minimum Path Sum

时间:2014-11-19 22:23:49      阅读:150      评论: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.


基本思路:

此题可以用动态规划算法解决。

到达grid[i][j]只有两种方式,从grid[i-1][j]向右移动或grid[i][j-1]向下移动。(PS:i >1 , j>1);

至于i = 1 和 j = 1 的情形只有一种方法可以到达,可以提前算好初始化。

然后利用上面的两种途径找最短的作为到达grid[i][j]的最短路径。


代码:

int minPathSum(vector<vector<int> > &grid) { //C++
        int rows = grid.size();
        if(rows == 0)
            return 0;
        int cols = grid[0].size();
        
        int upLine = 0;
        for(int i = 0; i < cols; i++)
            upLine += grid[0][i];    
        for(int i = 1; i< rows; i++)
            upLine += grid[i][cols-1];
        
        //init    
        vector<vector<int> > record ;
        for(int i = 0; i< rows; i++)
        {
            vector<int> tmp(cols,upLine);
            record.push_back(tmp);
        }
        
        int tmp = 0;
        for(int i = 0; i < cols; i++)
        {
            record[0][i] = tmp+grid[0][i];
            tmp = record[0][i];
        }
        tmp = 0;
        for(int j = 0; j < rows; j++)
        {
            record[j][0] =tmp + grid[j][0];
            tmp = record[j][0];
        }   
        
        for(int i = 1; i < rows; i++)
            for(int j = 1; j < cols; j++)
                record[i][j] = grid[i][j] + ((record[i][j-1] < record[i-1][j])?record[i][j-1]:record[i-1][j]);
                
        return record[rows-1][cols-1];
    }


[leetcode]Minimum Path Sum

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/41287703

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