友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

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.

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.

解题分析

0120 1

一图胜千言!

自底向上计算逐层每个元素的最小和。最后即可得出最小路径和。

思考题

尝试一下动态规划的思路。

参考资料

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
/**
 * Runtime: 1 ms, faster than 99.42% of Java online submissions for Triangle.
 * Memory Usage: 39.2 MB, less than 8.16% of Java online submissions for Triangle.
 */
public int minimumTotal(List<List<Integer>> triangle) {
    int[] sums = new int[triangle.size() + 1];
    for (int i = triangle.size() - 1; i >= 0; i--) {
        List<Integer> row = triangle.get(i);
        for (int j = 0; j < row.size(); j++) {
            sums[j] = Math.min(sums[j], sums[j + 1]) + row.get(j);
        }
    }
    return sums[0];
}