triangle(三角形)——leetcode
2017-05-23 16:51
323 查看
题目如下:
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 is11(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.
题解如下:
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 is11(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 static int minimumTotal(ArrayList<ArrayList<Integer>> triangle) { int []d=new int [1]; d[0]=triangle.get(0).get(0).intValue(); for(int i=1;i<triangle.size();i++) { d=dp(d,triangle,i); } int min=Integer.MAX_VALUE; for(int i=0;i<d.length;i++) { if(min>d[i]) { min=d[i]; } } return min; } public static int [] dp(int []d,ArrayList<ArrayList<Integer>> triangle,int now) { int []p=new int [d.length+1]; p[0]=d[0]+triangle.get(now).get(0).intValue(); p[now]=d[now-1]+triangle.get(now).get(now).intValue(); for(int j=1;j<now;j++) { int min=d[j-1]; if(d[j]<min) { min=d[j]; } p[j]=min+triangle.get(now).get(j).intValue(); } return p; }
相关文章推荐
- LeetCode-118-Pascal's Triangle(帕斯卡的三角形)
- leetcode:Triangle 三角形
- 【LeetCode——JAVA实现】119. pascals-triangle-ii(帕斯卡三角形 II)
- 【LeetCode-面试算法经典-Java实现】【120-Triangle(三角形)】
- [LeetCode]Triangle三角形
- [LeetCode]-Triangle 求三角形中从顶到底最短距离
- [Leetcode] triangle 三角形
- LeetCode题库解答与分析——#120. 三角形最小路径和Triangle
- 【LeetCode-面试算法经典-Java实现】【120-Triangle(三角形)】
- LeetCode Triangle 三角形(最短路)
- [LeetCode 120] - 三角形(Triangle)
- [LeetCode] Triangle 三角形
- LeetCode | Triangle(三角形路径和)
- Leetcode 120 Triangle 三角形最小路径和
- [LeetCode] Valid Triangle Number 合法的三角形个数
- LeetCode-Triangle -三角形-DP思想
- LeetCode(Oct30'12):Triangle 数字三角形
- Leetcode:Triangle 数字三角形
- leetcode Pascal's Triangle 帕斯卡尔三角形输出
- Leetcode-120_Triangle(三角形)—动态规划解法+记忆化搜索解法-【C++】