Leetcode 120 Triangle (Dynamic Programming Method)

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).

 

题目解析:

标准DP解法的题, 使用一个数组存结果就可以。

思路是from bottom to top, 先把最后一层存入数组, 然后依次递归上面一层求最小值, 这样最后数组index = 0的位置就是所求. 代码如下:

 

 1 public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) { //标准DP解法, 使用一个数组来存储结果
 2         int[] res = new int[triangle.size()];
 3         int lastSize = triangle.size() - 1;
 4         for(int i = 0; i < triangle.get(lastSize).size(); i++)
 5             res[i] = triangle.get(lastSize).get(i);
 6         
 7         for(int i = triangle.size() - 2; i >= 0; i--){
 8             for(int j = 0; j < triangle.get(i + 1).size() - 1; j++){
 9                 res[j] = triangle.get(i).get(j) + Math.min(res[j], res[j + 1]);
10             }
11         }
12         return res[0];
13     }

 

posted @ 2015-02-14 01:29  Sherry是小太阳  阅读(137)  评论(0编辑  收藏  举报