题目描述(Medium)
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
题目链接
https://leetcode.com/problems/triangle/description/
Example 1:
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
算法分析
设状态为
,表示从
出发,路径的最小和,则状态转移方程为
,从上到下可以考虑递归搜寻,但是时间复杂度太高,因此采用动态规划从下往上查找。
提交代码:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
for (int i = triangle.size() - 2; i >= 0; --i) {
for (int j = 0; j < i + 1; ++j) {
triangle[i][j] += min(triangle[i + 1][j],
triangle[i + 1][j + 1]);
}
}
return triangle[0][0];
}
};