LeetCode

这道题,采用动态规划算法。from top to down,把到每个节点的最小路径和都求出来。

下面是AC代码:

 1 /**
 2      * Given a triangle, find the minimum path sum from top to bottom. 
 3      * Each step you may move to adjacent numbers on the row below.
 4      * @param triangle
 5      * @return
 6      */
 7     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle){
 8         if(triangle==null || triangle.size()<=0)
 9             return 0;
10         if(triangle.size() == 1)
11             return triangle.get(0).get(0);
12         ArrayList<Integer> last = triangle.get(0);
13         ArrayList<Integer> curr = new ArrayList<Integer>();
14         //through Dynamic programming 
15         for(int i=1;i<triangle.size();i++){
16             curr.add(last.get(0)+triangle.get(i).get(0));
17             for(int j=1;j<i;j++){
18                 //get the smaller adjacent one on the last row 
19                 curr.add((last.get(j-1)<last.get(j)?last.get(j-1):last.get(j))+triangle.get(i).get(j));
20             }
21             curr.add(last.get(i-1)+triangle.get(i).get(i));
22             last.clear();
23             last.addAll(curr);
24             curr.clear();
25         }
26         
27         int min = Integer.MAX_VALUE;
28         for(int i=0;i<last.size();i++){
29             if(last.get(i)<min)
30                 min = last.get(i);
31         }
32         return min;
33     }
有问题可以和我联系,bettyting2010#163 dot com
原文地址:https://www.cnblogs.com/echoht/p/3703470.html