LeetCode -- Triangle 路径求最小和( 动态规划问题)

时间:2024-04-18 18:34:55

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、可以修改数组元素

 class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
for(int i = triangle.size()-; i >= ; --i)
{
for(int j = ; j < i+;++j)
{
if(triangle[i+][j]<triangle[i+][j+])
triangle[i][j] += triangle[i+][j];
else
triangle[i][j] += triangle[i+][j+];
} }
return triangle[][];
}
};

2、不能修改数组元素