美文网首页
120. Triangle

120. Triangle

作者: Al73r | 来源:发表于2017-11-07 09:37 被阅读0次

    题目

    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) {
            int N=triangle.size();
            int dp[N];
            for(int j=0; j<=N-1; j++){
                dp[j] = triangle[N-1][j];
            }
            for(int i=N-2; i>=0; i--){
                for(int j=0; j<=i; j++){
                    dp[j] = min(dp[j], dp[j+1]) + triangle[i][j];
                }
            }
            return dp[0];
        }
    };
    

    思考

    空间复杂度在本题中降低到了O(n)。

    相关文章

      网友评论

          本文标题:120. Triangle

          本文链接:https://www.haomeiwen.com/subject/caedmxtx.html