题目描述
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.
我的解法
解题思路
杨辉三角#118和最短路径#64的结合题目。还是使用动态规划的方法,在三角形边上的都等于上一个边上的点加上自身的代价,而三角形中间的点就等于在它上方的两个点中的最小的那个加上它的代价。
实现代码
1 | class Solution { |
Runtime: 4 ms, faster than 96.47% of C++ online submissions for Triangle.
Memory Usage: 9.9 MB, less than 56.52% of C++ online submissions for Triangle.