Problem
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
1 |
|
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
Explanation 1
-
To clearify, if current value is triangle[i][j] meaning that current row is i, current column is j, then we should go to the minimum of triangle[i+1][j] and triangle[i+1][j+1]. Here, we can use dynamic programming.
-
Using dynamic programming, we should also need to find out the base case. The base case is when we go to the last row, we just return the value of triangle[lastRow][col].
Solution 1
1 |
|
Explanation 2
-
We can also save space by creating a one dimensional array have size of the last column, and have values of the last row.
-
Starting from the second last row back to the first row, loop through its column, its current value triangle.get(row).get(col) changes to adding itself with the minimum value between the dp[col] and dp[col+1] and save the result to dp[col].
-
At the end, return dp[0].
Solution 2
1 |
|