120. Triangle

三角里的每一个数都是保存的从根节点到这个节点最短的距离。我目前的方法答案是对的,但是修改了Triangle本身,其实可以多保存一个,但是我懒得改了哈哈

 1     public int minimumTotal(List<List<Integer>> triangle) {
 2         int level = triangle.size();
 3         List<Integer> res = new ArrayList<Integer>();
 4         res.add(triangle.get(0).get(0));
 5         for(int i = 1; i < level; i++) {
 6             List<Integer> curLevel = triangle.get(i);
 7             int len = curLevel.size();
 8             curLevel.set(0, curLevel.get(0) + res.get(0));
 9             for(int j = 1; j < len - 1; j++) {
10                 curLevel.set(j, Math.min(res.get(j-1), res.get(j)) + curLevel.get(j));
11             }
12             curLevel.set(len - 1, curLevel.get(len - 1) + res.get(len - 2));
13             res = new ArrayList<Integer>(curLevel);
14         }
15         int min = Integer.MAX_VALUE;
16         for(int i = 0; i < res.size(); i++) {
17             min = (min < res.get(i))? min: res.get(i);
18         }
19         return min;
20     }

 

posted @ 2016-06-15 05:11  warmland  阅读(107)  评论(0编辑  收藏  举报