Leetcode Triangle

OpenSoucre發表於2014-06-22

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.

 

非常經典的動態規劃題

看到題目有點像樹的結構,可以考慮用深搜(DFS)去做,但每個結點總是共享一個子節點,有重疊子問題

如果從x和y到達最底部結點的最短路徑知道,則在選擇x和y結點時一定會選擇min(pathx ,pathy)最小的結點走,具有最優子結構特性

故可以考慮利用動態規劃解決(DP)

設決策變數為path[i][j],表示第i層的第j個結點到最底層的最短路徑

則path[i][j] = min(path[i+1][j],path[i+1][j+1]) + triangle[i][j] ,可以考慮滾動陣列的做法,由於底層的資料不會用到

利用新計算的值覆蓋原有的值,故只需要考慮一維陣列

path[j] = min(path[j] , path[j+1]) + triangle[i][j]; (j代表每層的第幾個結點)

注意計算時要從前往後計算,不然會改變原有的值,做完這題可以看一下從後往前計算的題Pascal's Triangle II

int minimumTotal(vector<vector<int> > &triangle) {
    int n = triangle.size();
    vector<int> path(triangle[n-1].begin(),triangle[n-1].end());
    for(int i = n-2; i>= 0; -- i){
        for(int j = 0 ; j < triangle[i].size(); ++ j){
            path[j] = min(path[j],path[j+1]) + triangle[i][j];
        }
    }
    return path[0];
} 

 

相關文章