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.

解题思路:

我用队列对整个三角形进行遍历,对当前点:

   1. 如果它是这行的第一个节点,那我们不弹出队首,只用它的值

   2. 如果它是这行的最后一个节点,那我们弹出队首后不能在取队首,因为那是到达这一行第一个节点的和。

   3. 如果它既不是第一个节点又不是最后一个节点,队首作为一个可能性,弹出队首后的队首又是一个新的可能,选择最小的那个

代码:

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        if(triangle.empty() || triangle[0].empty())
            return 0;
        queue<int> q;
        q.push(triangle[0][0]);
        for(int i = 1; i < triangle.size(); i++){
            for(int j = 0; j < triangle[i].size(); j++){
                if(j == 0){
                    q.push(triangle[i][j] + q.front());
                }else{
                    int p1 = q.front();
                    q.pop();
                    int p2 = ((j - 1) == (i - 1)) ? INT_MAX : q.front();
                    q.push(triangle[i][j] + min(p1, p2));
                }
            }
        }
        int minV = INT_MAX;
        while(!q.empty()){
            minV = min(minV, q.front());
            q.pop();
        }
        return minV;
    }
};

我看到更快更简洁的解法:

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        for(int i = triangle.size() - 2; i >= 0; --i)
        {
            for(int j = 0; j <= i; ++j)
            {
                triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]);
            }
        }
        return triangle[0][0];
    }
};

我觉得很可以

原文地址:https://www.cnblogs.com/yaoyudadudu/p/9171265.html