Problem Description
Given a triangle array, return the minimum path sum from top to bottom. At each step, you may move to an adjacent number on the row below. For example, if you are on index i on the current row, you can move to index i or i + 1 on the next row.
Key Insights
- Use dynamic programming to reduce overlapping subproblems.
- A bottom-up approach is most efficient by calculating the minimum path sums from the bottom row upward.
- This method reduces extra space usage to O(n) where n is the number of rows.
- The solution iteratively updates a dp array that eventually holds the minimum path sum at its first index.
Space and Time Complexity
Time Complexity: O(n^2) where n is the number of rows (each element is processed once). Space Complexity: O(n) extra space is used for the dp array storing one row of results.
Solution
A bottom-up dynamic programming approach is used to handle this problem. First, initialize a dp array as a copy of the last row of the triangle. Then, starting from the second-to-last row, update each element in the dp array by adding the current triangle element to the minimum of the two adjacent numbers from the row below (already stored in dp). By the time you reach the top row, dp[0] holds the minimum total path sum. The dp array is updated in place to ensure an O(n) space solution.