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).
解题:
直接从底部开始递归,不然就会像我一开始做的那样错在23rd case, 要比较最后一行的数字是否小。
代码如下:
int minimumTotal(vector<vector<int>>& triangle) {
for (int i = triangle.size() - 2; i >= 0; i--) {
for (int l = 0; l <= i; l++)
triangle[i][l] += min(triangle[i + 1][l], triangle[i + 1][l + 1]);
}
return triangle[0][0];
}