120. Triangle

每日一题 2019 - 04 - 30

题目:

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

1
2
3
4
5
6
[
[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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int len1 = triangle.size();
int len2 = 0 ;
for(int i = len1-2 ;i >= 0 ; i--)
{
len2 = triangle[i].size();
for(int j = 0 ; j < len2 ;j++)
{
triangle[i][j] += min(triangle[i+1][j],triangle[i+1][j+1]);
}
}
return triangle[0][0];
}
};
0%
undefined