# Leetcode 64. Minimum Path Sum

## 2. Solution

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

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


SnailTyan

• 擅长领域：
• 深度学习
• PyTorch
• OCR
• Docker
• Caffe