120.Triangle

你快乐吗?

Posted by bbkgl on September 26, 2019

120. Triangle

C++,动态规划。其实就是经典的dp题数塔问题,从下到上找最优解。

从下底层到最顶层,走到当前点的最短路劲都只和左下邻点以及右下邻点有关,所以得到本题的状态转移方程就是:

dp[i][j] = dp[i][j] + min(dp[i+1][j], dp[i+1][j+1])

代码如下:

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