*Triangle

题目

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

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

 

题解:

一道动态规划的经典题目。需要自底向上求解。

递推公式是: dp[i][j] = dp[i+1][j] + dp[i+1][j+1] ,当前这个点的最小值,由他下面那一行临近的2个点的最小值与当前点的值相加得到。

由于是三角形,且历史数据只在计算最小值时应用一次,所以无需建立二维数组,每次更新1维数组值,最后那个值里存的就是最终结果。

代码如下:

 

 1 public int minimumTotal(List<List<Integer>> triangle) {
 2     if(triangle.size()==1)
 3         return triangle.get(0).get(0);
 4         
 5     int[] dp = new int[triangle.size()];
 6 
 7     //initial by last row 
 8     for (int i = 0; i < triangle.get(triangle.size() - 1).size(); i++) {
 9         dp[i] = triangle.get(triangle.size() - 1).get(i);
10     }
11  
12     // iterate from last second row
13     for (int i = triangle.size() - 2; i >= 0; i--) {
14         for (int j = 0; j < triangle.get(i).size(); j++) {
15             dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j);
16         }
17     }
18  
19     return dp[0];
20 }

 

 

Reference:  http://www.programcreek.com/2013/01/leetcode-triangle-java/

 

 

 
 

 

posted @ 2015-07-03 15:58  Hygeia  阅读(132)  评论(0编辑  收藏  举报