Problem
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.
Example:
1 |
|
Explanation 1
-
Similar to 62. Unique Paths, we can create a
dp[][]
and use dynamic programming to solve this problem. -
The base case is
dp[0][0]
has the same value asgrid[0][0]
. The top row element will be its current value plus its left value,dp[0][col] = grid[0][col] + dp[0][col-1]
. The left most column element will be its current value plus its top value,dp[row][0] = grid[row][0] + dp[row-1][0]
. -
Now, we need to find the function. The function to calculate
dp[row][col]
will be its current value plus the minimum between its top value and its left value. In other word,dp[row][col] = grid[row][col] + min(dp[row-1][col], dp[row][col-1])
. -
The result will be the bottom right element of dp, which is
dp[row-1][col-1]
.
Solution 1
1 |
|
Explanation 2
-
We can save by space by using a 1 dimensional array
dp[]
that has sizecol
. Initialize all its elements asINT_MAX
exceptdp[0] = 0
. The reason we can use the 1 dimensional array is the current element’s min sum is only depends on its left and top element’s min sum. -
We don’t need to calculate the min sum of the first row and first column. Instead, when we iterate, if
c == 0
that means its first column, so we can updatedp[c] = grid[r][c] + dp[c]
. Else, we need to compare the left element’sdp[c-1]
and top element’sdp[c]
and choose the minimum one. If the current element is on the first row,dp[c]
is theINT_MAX
, so we will choose the minimumdp[c-1]
which is on the left side, then plus the current elementgrid[r][c]
, sodp[c] = grid[r][c] + min(dp[c], dp[c-1])
.
Solution 2
1 |
|
Explanation 3
- We can also save space by replacing the
grid
element. We need to iterate every element. If the current element isgrid[0][0]
, then wecontinue
. Else ifr == 0
, then we update the current element plus its left element. Else ifc == 0
, then we update the current element plus its top element. Else, we update the current element plus the minimum of its left and top element.
Solution 3
1 |
|