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

[LeetCode] Minimum Path Sum

时间:2014-07-26 01:42:16      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   strong   io   for   re   c   

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.

如果不是必须用stack,尽量不要用stack计算,因为总是会Time Limit Exceeded,就像下面代码:

class Solution {
public:
    int minPathSum(vector<vector<int> > &grid) {
        
        int m = grid.size();
        if(m<=0)
            return 0;
        int n = grid[0].size();
        stack<pair<pair<int,int>,int>> s;
        pair<int,int> temp(0,0);
        pair<pair<int,int>,int> rowCol_PathSum(temp,grid[0][0]);//存放行列值,以及从右上到此位置的PathSum值
        s.push(rowCol_PathSum);

        int minPaSum = -1;
        int row = 0,col = 0;
        while(!s.empty()){
           rowCol_PathSum = s.top();
           s.pop();
           row = rowCol_PathSum.first.first;
           col = rowCol_PathSum.first.second;
           int pathSum = rowCol_PathSum.second;
           if(row==m-1 && col == n-1)
           {
               if(minPaSum==-1 || rowCol_PathSum.second<minPaSum)
                   minPaSum =  pathSum;
                continue;
           }
           if(row<m-1)
           {
              rowCol_PathSum = make_pair(make_pair(row+1,col),pathSum+grid[row+1][col]);
              s.push(rowCol_PathSum);
           }
           if(col<n-1)
           {
              rowCol_PathSum = make_pair(make_pair(row,col+1),pathSum+grid[row][col+1]);
              s.push(rowCol_PathSum);
           }
        }//end while
        return minPaSum;
    }
};

看下面的方法,只需遍历一遍整个数组。DP

思路:定义一个与原数组一样大小的数组,数组(i,j)位置记录从(0,0)到(i,j)最小路径和,则要计算的从左上到右下的最小路径和就是所定义数组的右下角的元素:

class Solution {
public:
    int minPathSum(vector<vector<int> > &grid) {

        vector<vector<int> > minPathSumm = grid;
        int row = grid.size();
        if(row<=0)
            return 0;
        int col = grid[0].size();

        int i = 1;
        while(i<col)
        {
          minPathSumm[0][i] = grid[0][i]+minPathSumm[0][i-1];
          i++;
        }
        int j=1;
        while(j<row)
        {
          minPathSumm[j][0] = grid[j][0]+minPathSumm[j-1][0];
          j++;
        }


        for(int i=1;i<row;i++)
        {
           for(int j=1;j<col;j++)
           {
              minPathSumm[i][j] = min(minPathSumm[i-1][j],minPathSumm[i][j-1])+grid[i][j];
           
           
           }
        }
        return minPathSumm[row-1][col-1];
    }
};

 

[LeetCode] Minimum Path Sum,布布扣,bubuko.com

[LeetCode] Minimum Path Sum

标签:style   blog   color   strong   io   for   re   c   

原文地址:http://www.cnblogs.com/Xylophone/p/3869048.html

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