题目描述:
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
[ [2], [3,4], [6,5,7], [4,1,8,3] ]
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.
考察动态规划,可以想象为一棵树,在构造路径的时候,到达当前节点的路径长度为当前节点的值加上相邻的上层较小值。最直观的是构造一个二维矩阵,自顶向下构造路径,空间复杂度为 O(N^2);为了减少空间复杂度,可以自底向上构造,这样每一次的迭代结果覆盖前一次,最终0号元素就是最短路径值。
思考:自底向上的方法有点归并的感觉,总是将较小的和聚集到一个点。如果要求输出路径上的节点呢?如果底层的存储结果是树呢?
思维导图:
时间: 2024-11-01 01:40:56