leetcode[64]Minimum Path Sum

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.

class Solution {
public:
int minPathSum(vector<vector<int> > &grid) 
{
    int m=grid.size();
    if(m==0)return 0;
    int n=grid[0].size();
    vector<int> ivec(n);
    vector<vector<int>> f(m, ivec);
    f[0][0]=grid[0][0];
    for (int ki=1;ki<m;ki++)
    {
        f[ki][0]=f[ki-1][0]+grid[ki][0];
    }
    for(int kj=1;kj<n;kj++)
    {
        f[0][kj]=f[0][kj-1]+grid[0][kj];
    }
    for (int i=1;i<m;i++)
    {
        for (int j=1;j<n;j++)
        {
            f[i][j]=min(f[i-1][j],f[i][j-1])+grid[i][j];
        }
    }
    return f[m-1][n-1];
}
};

 

posted @ 2015-02-09 14:31  Vae永Silence  阅读(100)  评论(0编辑  收藏  举报