2-D Dynamic Programming Paths in a grid
542. Triangle
You are given a triangle of integers, triangle. Row i, counting from 0, holds i + 1 numbers. So the
top row holds one number, and each row holds one more than the row above it.
A path starts at the number in the top row and moves down one row at a time until it reaches the bottom
row. From triangle[i][j] it moves to either triangle[i + 1][j] or triangle[i + 1][j + 1]. In the
drawings, those are the number straight below and the number to the right of that one.
Return the smallest sum of the numbers on such a path.
Example 1
Input: triangle = [[5], [3, 7], [8, 4, 1], [2, 9, 6, 3]]
16Explanation: The cheapest path is 5 → 7 → 1 → 3, which adds up to 16. The path 5 → 3 → 4 → 6 starts with the smaller step but adds up to 18.
Example 2
Input: triangle = [[-1], [4, -3], [2, -6, 5]]
-10Explanation: The path -1 → -3 → -6 adds up to -10.
Example 3
Input: triangle = [[-7]]
-7Explanation: The triangle has one row, so the only path is the number -7 on its own.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ triangle.length ≤ 450triangle[i].length == i + 1-104 ≤ triangle[i][j] ≤ 104
Clarifying questions
What you would ask an interviewer before writing any code.