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:DP O(N^2) with O(N^2) 空间
|
|
解法2:DP O(N^2) with O(N) 空间
观察上面的解法可以看到,我们的2维数组实际上只用到了上一行的信息,由此我们可以对内存做一个小优化而达到O(N)的空间。
我们只保留上一行的每一个位置的最小值,需要一个大小为N的数组,N是总的行数,然后在计算中只要反复更新这个数组。
也就是说dp[i] = Math.min(dp[i - 1], dp[i]) + A[j][i] j是现在计算到的行数