![]() |
VOOZH | about |
Given a triangular array triangle[], find the minimum path sum from top to bottom. We start from the first cell in the first row, and at each step, we can move to one of the two adjacent cells in the next row — that is, if we are at index i in the current row, we can move to either index i or i + 1 in the next row.
The triangular array contains 1 cell in 1st row, 2 cells in 2nd row and so on.
Examples :
Input: triangle[][] = [[2],
[3, 7],
[8, 5, 6],
[6, 1, 9, 3]]
Output: 11
Explanation : The path is 2 -> 3 -> 5 -> 1, which results in a minimum sum of 2 + 3 + 5 + 1 = 11.Input: triangle[][] = [[3],
[6, 9],
[8, 7, 1],
[9, 6, 8, 2]]
Output: 15
Explanation: The path is 3 -> 9 -> 1 -> 2, which results in a minimum sum of 3 + 9 + 1 + 2 = 15.
Table of Content
At any position in the triangle, we can move only to one of the two adjacent positions in the next row.
So, to find the minimum path sum from a current cell (i, j), we need to consider both choices:
- Move to (i+1, j)
- Move to (i+1, j+1)
In order to find the answer for a cell in a row, we take the minimum among these two choices.
6
We observe that some of the subproblems overlap.
Like, in order to compute the answer for cell (i, j), we need answers for cells (i+1, j) and (i+1, j+1), and in order to compute the answer for cell (i, j+1), we need answers for cells (i+1, j+1) and (i+1, j+2). Here, the subproblems (i+1, j+1) is computed twice. Therefore, in order to avoid recomputing the same subproblems multiple times, we can store their results in a DP table and reuse them whenever needed.
6
In this approach, we iteratively calculate the answers starting from the smallest subproblems — the last row of the triangle. The answer for any row depends on the answers of the rows below it. Using the precomputed results from the next row, we can efficiently compute the minimum path sums for the current row and store them for further use, continuing this process upward until we reach the top.
6
In the above approach, we observe that in order to calculate the result for any cell in a row, we only need the answers of the next row in the triangle, specifically the two adjacent values directly below. Thus, while solving for a row, we use the answers of next row and store the answers for current one.
6