120. Triangle

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.

這道題如果從上往下走,可能性會相當的多,並不是一個好的選擇,我們可以嘗試從下往上走,將會更爲明瞭。
我畫一個圖輔助理解示意:
示意圖
從0開始算,一共有n層,每一層有n+1個數。從上往下看,這個三角形的可走路徑十分類似於一個二叉樹,每一次只能選擇相鄰的兩個節點往下走。反過來說,從下往上看,就是每次選擇相鄰的兩個數字,對應的向上的路徑只有一個。
要使得最終的結果路徑最短,也就是說要使每個子路徑最短。要想找到到第0層的最短路徑,也就是要找的到第1層的兩個數的最短路徑,然後比較到達第0層的路徑的長度求最小值;也就是要先找找第2層的三個數的最短路徑,將第2層的三個數分別與第1層的兩個數有路徑的相加、比較找到最小值……
所以我們可以我們利用一個數組result來存儲從第n層到當前層各個“節點”的最短路徑,從第n層開始,自己到自己的最短路徑是自己的數本身,所以result中的值即爲第n層各個數的值;之後計算第n-1層,第n層的相鄰的兩個節點對應第n-1層中的唯一確定的一個節點(也就是n-1層中的這個節點可以到達第n層的這兩個相鄰節點),所以使用
minresult[i],result[i+1])+triangle[n2][i]
來計算n-1層中唯一確定節點的最小值。利用循環求得從第n層到n-1層中每個節點的最短路徑,再利用一重循環,從第n層→第n-1層→第n-2層→……→第1層→第0層,從而求出從頂部到底部的最短路徑(最小值)。而最終的result[0]就是我們目標值。

參考代碼如下:

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        int n = triangle.size();
        int result[n];
        for(int i = 0; i < n; i++)
            result[i] = triangle[n-1][i];

        for(int i = n-2; i >= 0; i--) {
            for(int j = 0; j <= i; j++) {
                int min = result[j];
                if(result[j+1] < result[j])
                    min = result[j+1];
                result[j] = min + triangle[i][j];
            }
        }
        return result[0];
    }
};
發佈了30 篇原創文章 · 獲贊 1 · 訪問量 3811
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章