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)
- 120. Triangle
- 120. Triangle
- 120. Triangle
- 120. Triangle
- 120. Triangle
- 120. Triangle
- 120. Triangle
- 120.Triangle
- 120. Triangle
- 120. Triangle
- 120. Triangle
- 120. Triangle
- 120. Triangle
- 120. Triangle
- 120.Triangle
- 120. Triangle
- 120. Triangle
- 120. Triangle
- web前端-CSS Align(对齐) -020
- 社会契约论和先贤祠
- hihoCoder #1014 : Trie树
- ACdream 1738 世风日下的哗啦啦族I(分块)
- PMP在线考试
- 120. Triangle
- JavaSE IO流(2) 字节流
- Java应用定制工厂--jar转exe制作工具
- 从牟其中,到唐万新,到任正非:同根不同路
- 获取当前时间的代码
- 希腊字母发音对照表
- 微信小程序下拉筛选菜单WXDropDownMenu组件
- iOS 调用手机浏览器打开网页
- Python的关系运算符逻辑运算符和流程控制