Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note:Â You can only move either down or right at any point in time.
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Solution:
1. Recursion and Memoized
2. Tabulation
Same code converted to tabulation (Bottom Up)
Time and Space Complexity
Time Complexity: 𝑂(𝑛×𝑚)
The solution iterates through each cell in the grid exactly once.
Space Complexity: 𝑂(𝑛×𝑚) - dp size
3. Space optimized
Only Two Rows Needed:
In a grid-based dynamic programming problem where the solution for each cell depends only on the cells directly below and to the right, we only need the current row and the previous row for computation. This allows us to reduce the 2D DP array to two 1D arrays.
Overwriting Current Row:
By updating the curr array for the current row and then copying it to prev, we can reuse the space efficiently. The prev array holds the results of the previous row, which are required for the next row’s computations.
Time and Space Complexity
Time Complexity: 𝑂(𝑛×𝑚)
The solution iterates through each cell in the grid exactly once.
Space Complexity: đť‘‚(đť‘š)
The space is optimized to use two 1D arrays of size m, where m is the number of columns in the grid.