Minimum Path Sum

Description:

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.

Code:

 int minPathSum(vector<vector<int>>& grid) {

       int m = grid.size();

       assert(0!=m);

       int n = grid[0].size();

       assert(0!=n);

       

//pathSum[i][j]表示从元素(i,j)到元素(m-1,n-1)即右下角的路径和

       vector<vector<int>>pathSum(grid);

       for (int i = n-2; i >=0; --i)

            pathSum[m-1][i] += pathSum[m-1][i+1];

       for (int i = m-2; i >=0; --i)

            pathSum[i][n-1] += pathSum[i+1][n-1];

            

       for (int i = m-2; i >= 0; --i)

       {

           for (int j = n-2; j >= 0; --j)

           {

                    pathSum[i][j] += min(pathSum[i+1][j], pathSum[i][j+1]);

           }

       }

       return pathSum[0][0];

    }

 

你可能感兴趣的:(Path)