Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
思路:题目就是说从三角形顶端向下走,找到一条路使得和最小。这是个二维动态规划问题,我们将其分解为多个类似的子问题:寻找每个点到最低端的最小值,从底部开始向上找,这样就使得顶端点的值为我们所需要的最小值。
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];
}
};