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).

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.

一道典型的DP问题。对于某一层i,我们只要知道i-1层每个数字处的最小路径值,然后相应的选出小的那个加上第i层的对应数值,即可得到最新的最小路径值。注意最左和最右处的最小路径值只有一个来源(无法二选一)。最后得到最底层的所有最短路径值,选出最小的那个即可。

例如,对于示例中的三角,每一处的最小路径值为:

[
[2],
[5,6],
[11,10,13],
[15,11,18,16]
] 实际上,没有必要维护整个三角形(二维矩阵),而只需要维护两层的数据即可。比如如果要知道最底层的最小路径,只需要知道倒数第二层的最小路径。所以只需要两个数组即可。
代码如下:
     public int minimumTotal(List<List<Integer>> triangle) {
int[] dp = new int[triangle.size()];
int re = 0;
for(int i=0;i<triangle.size();i++) {
int[] temp = new int[triangle.size()];
for(int j=0;j<=i;j++) {
if(j==0) {
temp[j] = dp[j]+triangle.get(i).get(j);
re = temp[j];
}
else if(j==i)
temp[j] = dp[j-1]+triangle.get(i).get(j);
else
temp[j] = Math.min(dp[j],dp[j-1])+triangle.get(i).get(j);
re = Math.min(re, temp[j]);
}
dp = temp;
} return re;
}
05-11 11:03
查看更多