Question
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
The minimum path sum from top to bottom is 11
(i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
本题难度Medium。
DP
【复杂度】
时间 O(MN) 空间 O(1)
【思路】
这道题目类似于长方形的格子从最左上到最右下的最短距离,都是用DP解决。如果我们把三角形倒过来进行计算就更方便:
比如第2行第1个6
,该位置就是4
与1
的最小值与6
之和。最后只要返回最后一行那个元素值即可(都不需要额外分配空间)。
【代码】