Overview
Instead of starting at the top and branching down (which creates overlapping subproblems), we start at the bottom and work our way up.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number on the row below.
Instead of starting at the top and branching down (which creates overlapping subproblems), we start at the bottom and work our way up.
If we know the minimum path from the bottom to every node in row `R`, we can easily calculate the minimum path to every node in row `R-1`.
For an element at `(r, c)`, its two children are at `(r+1, c)` and `(r+1, c+1)`. So, `dp[c] = val + min(dp[c], dp[c+1])`.
Because we only ever need the values from the row immediately below us, we can overwrite a single 1D array of size `N` as we move upward.