120. Triangle
2017-01-17 13:24
253 查看
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
11).
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
if(triangle.size() == 0 || triangle == null){
return -1;
}
if(triangle.get(0).size() == 0 || triangle.get(0) == null){
return -1;
}
int n = triangle.size();
int[][] dp = new int
;
for(int i = 0; i < n; i++){
dp[n - 1][i] = triangle.get(n-1).get(i);
}
for(int i = n - 2; i > 0 ; i--){
for(int j = 0; j < i; j++){
dp[i][j] = Math.min(dp[i + 1][j], dp[i + 1][j + 1]) + triangle.get(i).get(j);
}
}
return dp[0][0];
}
自底向上,dp[i][j]代表从i,j点到底部最小的和
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).
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
if(triangle.size() == 0 || triangle == null){
return -1;
}
if(triangle.get(0).size() == 0 || triangle.get(0) == null){
return -1;
}
int n = triangle.size();
int[][] dp = new int
;
for(int i = 0; i < n; i++){
dp[n - 1][i] = triangle.get(n-1).get(i);
}
for(int i = n - 2; i > 0 ; i--){
for(int j = 0; j < i; j++){
dp[i][j] = Math.min(dp[i + 1][j], dp[i + 1][j + 1]) + triangle.get(i).get(j);
}
}
return dp[0][0];
}
自底向上,dp[i][j]代表从i,j点到底部最小的和
相关文章推荐
- 【eclipse插件】Checkstyle和Findbugs插件
- Echarts 获取后台数据 使用后台数据展示 柱形图
- TransactionScope线程安全问题整理
- JAVA中内存分配原理
- markdown基本语法
- Java的8种基本数据类型
- lucene初识
- 线性表顺序存储的基本操作
- 51nod 1242 斐波那契数列第n项
- 程序员1月书讯
- mongoose的增删改查操作
- MsgBox详解
- 广宇练习沃美功法不知不觉朝霞初生
- 485. Max Consecutive Ones
- shell中>/dev/null 2>&1是什么鬼?
- html标签详解(2)
- Hyperledger Fabric创世纪块源码解析
- iOS学习笔记-020.UIPageControl分页控件
- js检测关闭页面或浏览器
- java DateUtil 工具类 总结