[LeetCode]-Triangle 求三角形中從頂到底最短距離

Triangle


iven 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])+(i,j),當然最左和最右端的計算方式稍有變化。最後找出最小值即可。

採用滾動數組的方式,由於下層只和上層有關係,所以只需要記錄上層的信息即可,這樣就把O(n^2)的空間複雜度壓縮成了O(n)。
class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        int n=triangle.size();
        vector<int> f(n);
        
        f[0]=triangle[0][0];
        for(int i=1;i<n;i++){
            for(int j=triangle[i].size()-1;j>=0;j--){
                int mn;
                if(j==0){
                    mn=f[j];
                }
                if(j==i){
                    mn=f[j-1];
                }
                else{
                    mn=min(f[j-1],f[j]);
                }
                f[j]=mn+triangle[i][j];
            }
        }
        
        int min_sum=f[0];
        for(int i=1;i<n;i++)
            if(min_sum>f[i])min_sum=f[i];
        return min_sum;
    }
};


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章