LeetCode – Triangle (Java)
来源:互联网 发布:淘宝小号批量注册 编辑:程序博客网 时间:2024/05/14 16:04
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.
Top-Down Approach (Wrong Answer!)
This solution gets wrong answer! I will try to make it work later.
public class Solution { public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) { int[] temp = new int[triangle.size()];int minTotal = Integer.MAX_VALUE; for(int i=0; i< temp.length; i++){temp[i] = Integer.MAX_VALUE;} if (triangle.size() == 1) {return Math.min(minTotal, triangle.get(0).get(0));} int first = triangle.get(0).get(0); for (int i = 0; i < triangle.size() - 1; i++) {for (int j = 0; j <= i; j++) { int a, b; if(i==0 && j==0){a = first + triangle.get(i + 1).get(j);b = first + triangle.get(i + 1).get(j + 1); }else{a = temp[j] + triangle.get(i + 1).get(j);b = temp[j] + triangle.get(i + 1).get(j + 1); } temp[j] = Math.min(a, temp[j]);temp[j + 1] = Math.min(b, temp[j + 1]);}} for (int e : temp) {if (e < minTotal)minTotal = e;} return minTotal; }}
Bottom-Up (Good Solution)
We can actually start from the bottom of the triangle.
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {int[] total = new int[triangle.size()];int l = triangle.size() - 1; for (int i = 0; i < triangle.get(l).size(); i++) {total[i] = triangle.get(l).get(i);} // iterate from last second rowfor (int i = triangle.size() - 2; i >= 0; i--) {for (int j = 0; j < triangle.get(i + 1).size() - 1; j++) {total[j] = triangle.get(i).get(j) + Math.min(total[j], total[j + 1]);}} return total[0];}
0 0
- LeetCode – Triangle (Java)
- [Leetcode] Triangle (Java)
- LeetCode Triangle Java版本
- [LeetCode][Java] Triangle
- [leetcode]120. Triangle(Java)
- LeetCode – Triangle
- [Leetcode] Pascal's Triangle (Java)
- 【leetcode】Pascal's Triangle[java]
- [LeetCode][Java] Pascal's Triangle
- LeetCode|Pascal's Triangle-java
- leetcode:Pascal's Triangle 【Java】
- LeetCode题解–120. Triangle
- leetcode JAVA Triangle 难度系数3 3.42
- [Leetcode] Pascal's Triangle II (Java)
- 【leetcode】Pascal's Triangle II(Java)
- LeetCode(118) Pascal's Triangle (Java)
- LeetCode(119) Pascal's Triangle II (Java)
- [LeetCode][Java] Pascal's Triangle II
- zoj 2587 Unique Attack(最小割的唯一性判定)
- 【数据结构】 串的模式匹配算法KMP
- adduser添加用户和终端方向键tab键不能用的解决
- Pentaho需要的开发基础
- 一个功能的三种实现方法
- LeetCode – Triangle (Java)
- MFC中的数据类型
- C语言的数组名和对数组名取地址
- 一句话评论设计模式六大原则
- ubuntu与centos安装软件的不同点总结
- Android读取assests目录下文件
- Oracle备份为.dmp文件
- linux下的find文件查找命令与grep文件内容查找命令
- _beginthread, _beginthreadex与CreateThread的不同