120. Triangle

来源:互联网 发布:什么下载软件好 编辑:程序博客网 时间:2024/06/05 09:30

120. Triangle

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.

点击打开原题链接     

点击打开分析链接

分析:三角形看起来类似树形结构,假设x和y是k的两个子节点,一旦从底到x或者y的pathsum确定了,那么只要在x和y中取最小值,再加上k就是当前的pathsum。它是具有最优子结构性质的。这里从上到下的动态规划和从下到上的动态规划是不同的,如果top-bottom,你至少需要和这个三角形同样大小的结构来存储每个点的pathsum,空间复杂度是O(n^2)。如果是采用从下往上,我们有minpath[i][k]=min(minpath[i+1][k],minpath[i+1][k+1])+triangle[i][k],当你完全获取了第i层的信息后,第i+1层的值就不会再用到,因为计算第i-1层时只需用到第i层。所以,可以用O(n)的空间来存储,而不是O(n^2),即minpath[k]=min(minpath[k],minpath[k+1])+triangle[i][k].

第一种:top--to--bottom

空间:O(n^2)

第二种:bottom--to--up

空间:O(n)

0 0
原创粉丝点击