LeetCode 120. Triangle 解题报告

来源:互联网 发布:windows帮助与支持 编辑:程序博客网 时间:2024/05/29 12:18

120. Triangle

My Submissions
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

Show Tags
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
原创粉丝点击