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

分析

找出一個三角形從頂?shù)降鬃疃搪窂?。很簡單的動態(tài)規(guī)劃問題,從上到下,依次計算到當前行左邊路線和右邊路線哪個是最短距離。不過需要兩端的點只有一條路,需要另處理。
當然也可以從下到上,更方面了。

int minimumTotal(int** triangle, int triangleRowSize, int *triangleColSizes) {
    int ans=0;
    for(int i=1;i<triangleRowSize;i++)
    {
        triangle[i][0]=triangle[i-1][0]+triangle[i][0];
        for(int j=1;j<triangleColSizes[i]-1;j++)
        {
            int left=triangle[i-1][j-1]+triangle[i][j];
            int right=triangle[i-1][j]+triangle[i][j];
            if(left<right)
                triangle[i][j]=left;
            else
                triangle[i][j]=right;
        }
        triangle[i][ triangleColSizes[i]-1 ]=triangle[i-1][ triangleColSizes[i]-2 ]+triangle[i][ triangleColSizes[i]-1 ];
    }
    ans=triangle[triangleRowSize-1][0];
    for(int j=1;j<triangleColSizes[triangleRowSize-1];j++)
        if(triangle[triangleRowSize-1][j]<ans)
            ans=triangle[triangleRowSize-1][j];
    
    return ans;
}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容