LeetCode 120. Triangle 解题报告
来源:互联网 发布:windows帮助与支持 编辑:程序博客网 时间:2024/05/29 12:18
Total Accepted: 62827 Total Submissions: 213725 Difficulty: Medium
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.
Subscribe to see which companies asked this question
Have you met this question in a real interview?
Yes
No
Discuss
显然DP求解。Java的List不支持下标操作显然是Java的天生缺陷,写出来又长又难看,而且十分容易写错下标。
我的AC代码
public class Triangle {/** * @param args */public static void main(String[] args) {List<List<Integer>> dp = new ArrayList<List<Integer>>();List<Integer> l1 = new ArrayList<Integer>();List<Integer> l2 = new ArrayList<Integer>();List<Integer> l3 = new ArrayList<Integer>();l1.add(-1);l2.add(2);l2.add(3);l3.add(1);l3.add(-1);l3.add(-3);dp.add(l1);dp.add(l2);dp.add(l3);System.out.print(minimumTotal(dp));}public static int minimumTotal(List<List<Integer>> triangle) {if(triangle.size() == 0) return 0;List<List<Integer>> dp = new ArrayList<List<Integer>>();dp.add(triangle.get(0));for (int i = 1; i < triangle.size(); i++) {List<Integer> dpl = new ArrayList<Integer>();List<Integer> list = triangle.get(i);List<Integer> dpup = dp.get(i-1);dpl.add(list.get(0) + dpup.get(0));for (int j = 1; j < list.size() - 1; j++) {int a = dpup.get(j-1) ,b = dpup.get(j);int min = a > b ? b : a;dpl.add(list.get(j) + min);}dpl.add(list.get(list.size() - 1) + dpup.get(dpup.size() - 1));dp.add(dpl);}List<Integer> last = dp.get(dp.size() - 1);int min = last.get(0);for (int i = 1; i < last.size(); i++) if(last.get(i) < min) min = last.get(i);return min; }}
0 0
- [leetcode] 120. Triangle 解题报告
- LeetCode 120. Triangle 解题报告
- LeetCode 120. Triangle 解题报告
- [Leetcode] 120. Triangle 解题报告
- Leetcode Triangle 解题报告
- 【LeetCode】Triangle 解题报告
- [LeetCode] Triangle 解题报告
- LeetCode解题报告 120. Triangle [medium]
- [LeetCode],Pascal's Triangle, 解题报告
- 【LeetCode】Pascal's Triangle & II 解题报告
- [leetcode] 118. Pascal's Triangle 解题报告
- 【LeetCode】Pascal's Triangle 解题报告
- 【LeetCode】Pascal's Triangle II 解题报告
- leetcode 118. Pascal's Triangle 解题报告
- [Leetcode] 118. Pascal's Triangle 解题报告
- 【LeetCode】611.Valid Triangle Number解题报告
- 【LeetCode】Pascal's Triangle II 解题报告
- 2954 Triangle 解题报告
- 2016年的目标
- 如何准备性能测试数据
- leetcode第19题——*Remove Nth Node From End of List
- [Lintcode]Maximum Subarray
- 佛祖保佑,永无BUG
- LeetCode 120. Triangle 解题报告
- u3d:后期屏幕渲染特效
- 3、Maven的项目的目录结构简介和一些常用命令
- Android 性能优化之使用线程池处理异步任务
- Dockerfile语法总结
- ios博客浏览工具
- Android开发中一些被冷落但却很有用的类和方法
- 5位数逆序排列
- 关于cgywin下执行找不到make命令的问题