LeetCode 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 is 11
(i.e., 2 + 3 + 5 + 1 = 11).
1 public class Solution { 2 public int minimumTotal(List<List<Integer>> triangle) { 3 int[] lastsum=new int[triangle.size()+1]; 4 int[] thissum=new int[triangle.size()+1]; 5 int sum=Integer.MAX_VALUE; 6 if (triangle.isEmpty()) return 0; 7 for (int i = 0; i < lastsum.length; i++) { 8 lastsum[i]=sum; 9 thissum[i]=sum; 10 } 11 lastsum[0]=0; 12 int j; 13 for (List<Integer> list : triangle) { 14 for (int i = 0; i < list.size(); i++) { 15 if (i==0) { 16 j=0; 17 }else { 18 j=i-1; 19 } 20 thissum[i]=list.get(i)+Math.min(lastsum[i],lastsum[j]); 21 22 } 23 for (int i = 0; i < lastsum.length; i++) { 24 lastsum[i]=thissum[i]; 25 } 26 } 27 for (int i : lastsum) { 28 if (i<sum) sum=i; 29 } 30 return sum; 31 } 32 }