120. Triangle
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
1 | For example, given the following triangle |
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.
题意:
给定一个三角形,找到从上到下的最小路径求和。每一步你可以移动到下面一行相邻的数字**,特别注意是相邻的数字。
只用O(n)额外的空间来做,其中n是三角形中的总行数。
思路:
从三角形的底部往顶部走进行遍历,一次查找最小元素,这样当查找本行的最小和时,只需与下一行相邻元素相加的和进行比较求出最小和。
这道题最主要需要学的地方就是换角度思考问题,把上到的下的查找转换为下到上的查找,从而降低代码逻辑难度。
1 | class Solution { |
下面是从上往下遍历三角形的过程中,求出当前行每个元素与上层元素相加的最小和,要考虑的边界问题相对较多,代码繁琐。
1 | class Solution { |