120. Triangle
2016-02-10 19:30
330 查看
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.
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.
public int minimumTotal(List<List<Integer>> tr) { if(tr == null || tr.size() == 0) return 0; int[] min = new int[tr.size()]; //记录每行的最小值 min[0] = tr.get(0).get(0); for(int i = 1;i < tr.size();i++){ //迭代计算每行的最小sum int last = Integer.MAX_VALUE; List<Integer> cur = tr.get(i); for(int j = 0;j < cur.size()-1;j++){ int tmp = Math.min(min[j],last); last = min[j]; min[j] = cur.get(j)+tmp; } min[cur.size()-1] = cur.get(cur.size()-1)+last; } int minum = min[0]; for(int i = 1;i < tr.size();i++){ //计算最小sum if(min[i] < minum) { minum = min[i]; } } return minum; }
相关文章推荐
- SparseAutoEncoder 稀疏编码详解(Andrew ng课程系列)
- Atitit。Tree文件解析器的原理流程与设计实现 java c# php js
- Atitit。Tree文件解析器的原理流程与设计实现 java c# php js
- 算法练习 动态规划 装配线调度
- hdu 1005 矩阵快速幂模板题
- Atitit。Tree文件解析器的原理流程与设计实现 java c# php js
- 【Linux学习014】特殊权限
- spi裸板程序
- Codeforces Round #342 (Div. 2)-C. K-special Tables(模拟)
- 子元素滚动不影响父元素
- 子元素滚动不影响父元素
- The Java™ Tutorials — Concurrency :Thread Objects 线程对象
- 移动网络
- Linux - 命令
- 活着就为改变世界 -- 目录
- 杭电ACM1408——盐水的故事
- Atitit. 真正的全中国文字attilax易语言的特点以及范例
- 蓝桥杯 算法训练 ALGO-3 K好数
- 18 图形界面
- Atitit. 真正的全中国文字attilax易语言的特点以及范例