给定一个只含非负整数的m*n网格,找到一条从左上角到右下角的可以使数字和最小的路径。
class Solution { public: /* * @param grid: a list of lists of integers * @return: An integer, minimizes the sum of all numbers along its path */ int minPathSum(vector<vector<int>> &grid) { // write your code here int row=grid.size(); int col=grid[0].size(); for(int j=col-2;j>=0;j--) { grid[row-1][j]+=grid[row-1][j+1]; } for(int i=row-2;i>=0;i--) { for(int j=col-1;j>=0;j--) { if(j==col-1) { grid[i][j]+=grid[i+1][j]; continue; } grid[i][j]+=min(grid[i][j+1],grid[i+1][j]); } } return grid[0][0]; } };
原文地址:https://www.cnblogs.com/zslhg903/p/8367864.html
时间: 2024-10-21 22:09:33