Triangle — LeetCode 120 Python Solution
- Problem
- #120
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below.
Example
- Input
- triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
- Output
- 11
- Explanation
- The triangle looks like:
Python solution
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
n = len(triangle)
f = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(i + 1):
f[i][j] = min(f[i + 1][j], f[i + 1][j + 1]) + triangle[i][j]
return f[0][0]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n), where n is the number of rows in the triangle auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 120. Triangle is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
On a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 120. Triangle?
- LeetCode 120. Triangle is rated Medium on LeetCode.
- What is the time complexity of LeetCode 120. Triangle?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 120. Triangle?
- The Python solution on this page uses O(n), where n is the number of rows in the triangle auxiliary space.
- What topics does LeetCode 120. Triangle cover?
- LeetCode 120. Triangle is tagged Array and Dynamic Programming on LeetCode.