Minimum Path Sum
You can solve this problem by using Dynamic Programming. Here’s the step-by-step process:
Initialization: Create a 2D array
dp
with the same dimensions as the grid, wheredp[i][j]
will represent the minimum sum to reach the cell(i, j)
from the top-left corner.Base Case: The minimum sum to reach the top-left corner itself is the value at that cell, so
dp[0][0] = grid[0][0]
.Calculate the First Row and Column: Since you can only move right or down, the values in the first row and first column can be calculated easily by summing the previous value with the current grid value.
Iterate Through the Grid: Now, for the rest of the cells
(i, j)
, you can only reach them from the left(i, j-1)
or from above(i-1, j)
. So, take the minimum of these two paths and add the value at the current grid cell.Return the Result: The value at
dp[m-1][n-1]
will give you the minimum path sum from the top-left to the bottom-right corner.
Here’s the code:
|
|
This code will give you the minimum path sum, as required by the problem. The time complexity of this solution is ( O(m \cdot n) ), where ( m ) and ( n ) are the number of rows and columns in the grid, respectively. The space complexity is also ( O(m \cdot n) ), as we are using a 2D array to store our results.
minimize something : optimization problem
Greedy appraoch: Exmaple 1 : leads to wrong answer Bruteforce : Time complexity is not good What approach can be used to find the optimal solution?
Find one solution that is minimal sum.
DP Approach
[1, 3, 1] => [1, 4, 5]
We calculated the prefix sum.
Optimal substructure
Overlapping subproblems Identify the state? cost(r, c) = [() ()]
cost(1, 1) = 1 cost(1, 2) = 1 + 3 = 4 cost(1, 3) = 4 + 1 = 5
cost(r, c) = grid[r][c] + min(cost(r, c-1), cost(r-1, c))
dp table with mxn
T:O(N^2) S:O(MxN)
|
|