DP问题
第一遍做的时候是top-down 当前这层的数值从上一层得到,非常麻烦的地方在于需要判断这个元素是否在一层两端。
bottom-up方法就比较直观,不需要考虑边界,因为对于地n-1行arr [ i ] = min(arr[ i ],arr [ i + 1] )+ 当前
bottom-up:
public class Solution { public int minimumTotal(List<List<Integer>> triangle) { if ( triangle == null || triangle.size() == 0 || triangle.get(0).size() == 0) return 0; List <Integer> midRes = new ArrayList < Integer> (); int size = triangle.size(); midRes = triangle.get(size-1); for ( int i = size-2; i >= 0; i -- ){ for ( int j = 0; j <= i; j ++){ midRes.set(j, Math.min(midRes.get(j),midRes.get(j+1)) + triangle.get(i).get(j)); } } return midRes.get(0); } }
public class Solution { public int minimumTotal(List<List<Integer>> triangle) { if ( triangle == null || triangle.size() == 0 || triangle.get(0).size() == 0) return 0; List <Integer> midRes = new ArrayList < Integer> (); midRes.add (triangle.get(0).get(0)); for ( int i = 0; i < triangle.size(); i ++ ){ for ( int j = i; j >= 0; j -- ){ if ( j == i ){ if ( i != 0 ){ midRes.add( midRes.get(j-1) + triangle.get(i).get(j) ); } } else if ( j != 0 ){ midRes.set( j, triangle.get(i).get(j) + Math.min(midRes.get(j), midRes.get(j-1))); } else midRes.set( j, triangle.get(i).get(j) + midRes.get(j) ); } } Collections.sort(midRes); return midRes.get(0); } }