-
-
Notifications
You must be signed in to change notification settings - Fork 50.5k
Expand file tree
/
Copy pathtriangle.py
More file actions
42 lines (32 loc) · 1.38 KB
/
triangle.py
File metadata and controls
42 lines (32 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from __future__ import annotations
def minimum_total(triangle: list[list[int]]) -> int:
"""
Return the minimum path sum from top to bottom of a triangle.
Each step you may move to adjacent numbers on the row below.
The input must be a proper triangle: len(row i) == i + 1.
>>> minimum_total([[2],[3,4],[6,5,7],[4,1,8,3]])
11
>>> minimum_total([[-10]])
-10
>>> minimum_total([[1],[2,3]])
3
>>> minimum_total([]) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
ValueError: triangle must be non-empty and well-formed
>>> minimum_total([[1],[2]]) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
ValueError: triangle must be non-empty and well-formed
"""
# Basic validation: non-empty and proper "triangle" shape
if not triangle or any(len(row) != i + 1 for i, row in enumerate(triangle)):
raise ValueError("triangle must be non-empty and well-formed")
# Start from the last row and fold upwards. dp[j] stores the minimum path
# sum from row r to the bottom starting at column j.
dp = triangle[-1][:] # copy so we don't mutate the input
for r in range(len(triangle) - 2, -1, -1):
for c in range(r + 1):
dp[c] = triangle[r][c] + min(dp[c], dp[c + 1])
return dp[0]
if __name__ == "__main__":
import doctest
doctest.testmod()