题目:
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.
链接: http://leetcode.com/problems/triangle/
6/7/2017
11ms, 38%
2种方法,第二种是参考别人的,虽然第15行有arraylist.remove操作,但是运行时间居然更短。
第一种:建一个初始长度为length + 1的arraylist,初始化为0,每一层从后向前赋值,并在内循环结束后删除多余的第一个元素。
1 public class Solution { 2 public int minimumTotal(List<List<Integer>> triangle) { 3 int length = triangle.size(); 4 List<Integer> dp = new ArrayList<Integer>(); 5 for (int i = 0; i <= length; i++) { 6 dp.add(0); 7 } 8 9 for (int i = length - 1; i >= 0; i--) { 10 List<Integer> row = triangle.get(i); 11 int numElem = i; 12 for (int j = numElem; j >= 0; j--) { 13 dp.set(j + 1, row.get(j) + Math.min(dp.get(j), dp.get(j + 1))); 14 } 15 dp.remove(0); 16 } 17 return dp.get(0); 18 } 19 }
第二种,建一个辅助arraylist,初始值为最后一行的所有元素。内循环是每一行从头赋值,不需要管最后一个元素。
1 public class Solution { 2 public int minimumTotal(List<List<Integer>> triangle) { 3 int length = triangle.size(); 4 List<Integer> dp = new ArrayList<Integer>(triangle.get(length - 1)); 5 6 for (int i = length - 2; i >= 0; i--) { 7 List<Integer> row = triangle.get(i); 8 for (int j = 0; j < row.size(); j++) { 9 dp.set(j, row.get(j) + Math.min(dp.get(j), dp.get(j + 1))); 10 } 11 } 12 return dp.get(0); 13 } 14 }
更多讨论