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

設狀態為 f[i][j],表示根到節點(i,j)的最短路徑,狀態方程:
f[i][j] = min(f[i-1,j-1],f[i-1,j]) + tringal[i,j]
使用一維數組實現:

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int height = triangle.size();
        if(height == 0){
            return 0;
        }
        
        int [] minPath = new int[height+1];
        List<Integer> layer = triangle.get(0);
        minPath[0] = Integer.MAX_VALUE;
        minPath[1] = layer.get(0);
        int minPathValue = Integer.MAX_VALUE;
        for(int i = 1; i<height; i++){
            layer = triangle.get(i);
            minPath[i+1] = Integer.MAX_VALUE;
            for(int j=i+1; j>0; j--){
                minPath[j] = Math.min(minPath[j-1], minPath[j]) + layer.get(j-1);
            }
        }
        for(Integer i: minPath){
            minPathValue = Math.min(minPathValue, i);
        }
        
        return minPathValue;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,779評論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,949評論 0 23
  • 課程目標 掌握常見 CSS 選擇器的用法 對選擇器優先級有一定認識 課程任務 1. CSS選擇器常見的有幾種? i...
    Timmmmmmm閱讀 250評論 0 0
  • 如果還有可能,我還想來這,看看這個靠窗而坐的女孩,吃著蘋果看著書。很恬!
    jac1king閱讀 212評論 0 1
  • 中午休息,姜潤和蘇曉坐在一旁,翹起二踉腿,暢談“美好未來”。 “你看看樓下一點點奶茶店,每天都排好長的隊,營業額不...
    小星晨閱讀 345評論 1 3