原题链接
https://leetcode.com/problems/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.
给出一个三角形(数据数组),找出从上往下的最小路径和。每一步只能移动到下一行中的相邻结点上。
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).
则从上至下最小路径和为11(即,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.
如果你可以只使用O(n)的额外空间(n是三角形的行数),可以获得奖励分数。
解题思路
简单的动态规划,唯一的问题是题目里给的空间复杂度的要求。先来说动态规划,当选择下面一层中的数字时,我们只能选择相邻的数字。什么是相邻的数字呢?拿上面的例子来说,对于2,下一行里3和4是相邻的;对于3来说,6和5>是相邻的;对于4来说,5和7是相邻的;对于6来说,4和1是相邻的;对于5来说,1和8是相邻的;对于7来说,8和3是相邻的;对于4/1/8/3来说,没有下一行所以没有相邻数字了。如果我们把数字都对应到数据在每一行中的下标上,可
以很容易发现,对于一个data[i][j],和它相邻的数字就是data[i+1][j]和data[i+1][j+1]。这样一来问题就简单了。假如我们用minimus[i][j]来表示从第i行第j列处的数字开始往下到最后一层的最小路径和,那么有
minimus