64. Minimum Path Sum
Problem description:
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.1
2
3
4
5
6
7
8
9
10Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
Solution:
- 2D array DP
Use an extra matrixdp
of the same size as the original matrix. In this matrix,dp(i, j)
represents the minimum sum of the path from the index(i, j)
to the bottom rightmost element. We start by initializing the bottom rightmost element ofdp
as the last element of the given matrix. Then for each element starting from the bottom right, we traverse backwards and fill in the matrix with the required minimum sums. Now, we need to note that at every element, we can move either rightwards or downwards. Therefore, for filling in the minimum sum, we use the equation:
dp(i,j)=grid(i,j)+min(dp(i+1,j),dp(i,j+1))
1 | class Solution { |
time complexity: O(mn)
space complexity: O(mn)
- 1D array
We can do the same work using adp
array of the row size, since for making the current entry all we need is the dp entry for the bottom and the right element. Thus, we start by initializing only the last element of the array as the last element of the given matrix. The last entry is the bottom rightmost element of the given matrix. Then, we start moving towards the left and update the entrydp(j)
as:
dp(j)=grid(i,j)+min(dp(j),dp(j+1))
We repeat the same process for every row as we move upwards. At the end dp(0)dp(0) gives the required minimum sum.
1 | class Solution { |
time complexity: O(mn)
space complexity: O(n)