【Leetcode】120. Triangle

Description

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.

Solution

1
2
3
4
5
6
7
8
9
public int minimumTotal(List<List<Integer>> triangle) {
int[] A = new int[triangle.size() + 1];
for (int i = triangle.size() - 1; i>=0; i--) {
for (int j = 0; j < triangle.get(i).size(); j++) {
A[j] = Math.min(A[j], A[j + 1]) + triangle.get(i).get(j);
}
}
return A[0];
}

Analyse

这里分析了几点情况如下,其实思路就是从低往高找,思路如下所示。如果上一层是第0个,下面可以走的就是第0个和第1个,这样就是triangle.get(i).get(j)对应下面的A[j]和A[j+1],所以要在A[j]和A[j+1]中选出一个min值,这个值用来更新。初始化的时候就是triangle.size() + 1的数组大小,因为j的范围要到triangle.get(i)里的大小加一,相当于从底部开始更新,更新到最上面,结果就是A[0]的返回。这里的复杂度是O(n^2),因为这里两重for循环。

坚持原创技术分享,您的支持将鼓励我继续创作!