首页 > 其他 > 详细

LeetCode - Trangle

时间:2014-05-02 12:18:20      阅读:380      评论:0      收藏:0      [点我收藏+]

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

下面是AC代码:

bubuko.com,布布扣
 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     }
bubuko.com,布布扣

 

LeetCode - Trangle,布布扣,bubuko.com

LeetCode - Trangle

原文:http://www.cnblogs.com/echoht/p/3703470.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!