[leedcode 120] Triangle
2015-07-22 22:45
381 查看
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
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 class Solution { public int minimumTotal(List<List<Integer>> triangle) { //空间复杂度为O(n),n为三角形的层数,时间复杂度为O(K),K为整个三角形中数字的个数 //从底向上计算,动态规划,题意是只能取相邻的,因此状态转移方程可以求得 int n=triangle.size(); int dp[]=new int ; for(int i=n-1;i>=0;i--){ for(int j=0;j<=i;j++){ if(i==n-1){ dp[j]=triangle.get(i).get(j); }else{ dp[j]=Math.min(dp[j],dp[j+1])+triangle.get(i).get(j); } } } return dp[0]; } }
相关文章推荐
- 顶级操盘手是怎样准确把握入场时机的
- Coding 代码管理快速入门(转)
- epoll源码实现分析
- Linux kernel 分析之十三:kbuild系统-编译到内核和编译成模块的区别
- try语句的基本用法
- swt
- 使用nohup在后台运行scp
- can you find it?
- 经典错误---xxx.hbm.xml文件中[properties] not found getter or setter
- 移动端 图片不变形
- javascript日历控件——纯javascript版
- android如何阻止app_name在标题栏中闪现
- Navigation Bar色设置
- route , 双网卡实现同时访问内外网。
- 坚持
- mysql语句优化
- 杭电ACM1277——全文检索~~AC自动机算法
- NET技术
- 转载
- android shape的使用详解以及常用效果(渐变色、分割线、边框、半透明阴影效果等)