只初始化(0,0)
class Solution { public: int minPathSum(vector<vector<int>>& grid) { int height = grid.size(); int width = grid[0].size(); vector<vector<int>> result(height,vector<int>(width)); result[0][0] = grid[0][0]; for(int i = 0;i < height;i++){ for(int j = 0;j < width;j++){ if(i != 0 && j != 0) result[i][j] = min(result[i][j-1],result[i-1][j]) + grid[i][j]; else if(i == 0) result[i][j] = result[i][j-1] + grid[i][j]; else result[i][j] = result[i-1][j] + grid[i][j]; } } return result[height-1][width-1]; } };
初始化第一行,第一列
class Solution { public: int minPathSum(vector<vector<int>>& grid) { int length = grid.size(); if(length <= 0) return 0; int width = grid[0].size(); vector<vector<int>> result(length,vector<int>(width)); result[0][0] = grid[0][0]; for(int i = 1;i < width;i++) result[0][i] = result[0][i-1] + grid[0][i]; for(int j = 1;j < length;j++) result[j][0] = result[j-1][0] + grid[j][0]; for(int i = 1;i < length;i++){ for(int j = 1;j < width;j++){ result[i][j] = min(result[i-1][j],result[i][j-1]) + grid[i][j]; } } return result[length-1][width-1]; } };