Triangle leetcode java


題目

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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM