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

思路:

思路一是利用树的结果进行递归,唯一区别是采用数组的形式存储树。 思路二是由于思路一时间开销太大,于是可以采用DP的方式减少计算次数。

题目:

思路一:时间开销太大

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return min(triangle, 0, 0);
    }
    
    int min(vector<vector<int>> &triangle, int level, int i)
    {
        if(level == triangle.size()-1)
        {
            return triangle[level][i];
        }
        else
        {
            int left = min(triangle, level + 1, i);
            int right = min(triangle, level + 1, i+1);
            
            return left<right?(left+triangle[level][i]):(right+triangle[level][i]);
        }
    }
};

思路二:

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(triangle.size() == 0)
        {
            return 0;
        }
        else if(triangle.size() == 1)
        {
            return triangle[0][0];
        }
        
        int dp[triangle.size()][triangle.size()];
        
        for(int i = 0; i < triangle.size(); i++)
        {
            dp[triangle.size()-1][i] = triangle[triangle.size()-1][i];
        }
        
        for(int i = triangle.size()-2; i >= 0; i--)
        {
            for(int j = 0; j <= i; j++)
            {
                dp[i][j] = (dp[i+1][j]<dp[i+1][j+1]?dp[i+1][j]:dp[i+1][j+1]) + triangle[i][j];
            }
        }
        
        return dp[0][0];
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11881773
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞