The problem asks for the minimum path sum from the top-left to the bottom-right of a grid, moving only right or down. Recursion allows us to break the problem into smaller subproblems: the minimum path sum to a cell is the cell’s value plus the minimum of the path sums to its top or left neighbor. We use recursion to explore all possible paths, handling edge cases for the first row and column.
To avoid redundant calculations in recursion, we use memoization to store the minimum path sum for each cell. This ensures each subproblem is solved only once, making the solution efficient for large grids.
Instead of using recursion or extra memory, we can solve the problem by updating the grid directly. Each cell in the grid will store the minimum path sum to reach that cell from the top-left, using only previously computed values. This approach leverages the fact that the minimum path to each cell depends only on its top and left neighbors.
classSolution {
public:int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
for (int row =0; row < m; ++row) {
for (int col =0; col < n; ++col) {
if (row ==0&& col ==0) continue;
elseif (row ==0) grid[row][col] += grid[row][col -1];
elseif (col ==0) grid[row][col] += grid[row -1][col];
else grid[row][col] += min(grid[row -1][col], grid[row][col -1]);
}
}
return grid[m -1][n -1];
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintminPathSum(int[][] grid) {
int m = grid.length, n = grid[0].length;
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
if (row == 0 && col == 0) continue;
elseif (row == 0) grid[row][col]+= grid[row][col - 1];
elseif (col == 0) grid[row][col]+= grid[row - 1][col];
else grid[row][col]+= Math.min(grid[row - 1][col], grid[row][col - 1]);
}
}
return grid[m - 1][n - 1];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defminPathSum(self, grid: list[list[int]]) -> int:
m, n = len(grid), len(grid[0])
for row in range(m):
for col in range(n):
if row ==0and col ==0:
continueelif row ==0:
grid[row][col] += grid[row][col -1]
elif col ==0:
grid[row][col] += grid[row -1][col]
else:
grid[row][col] += min(grid[row -1][col], grid[row][col -1])
return grid[m -1][n -1]