[leet code] 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.

=================

Analysis:

It is a tougth question (for me), we do not have the "bottom-up" idea.


If we start calculate the path sums from top of the triangle to the bottom, we have to tranverse all the possible paths (O(2^n)).  Because, if we only choose the smaller adjacent number in the next level, we cannot ensure the sum of the WHOLE path is smaller than the other one.
However, if we start calculate the path sums from the bottom of the triangle to the top, we can always choose the current smaller path.  This is because, in this approach, we are not comparing to number in the previous level, but the sums of these two paths till previous level. (O(n^2))


After having this "bottom-up" idea, the implementation is strait forward.  We need an array to keep the path sums, but only the path with smallest sum will reach the top level.

public class Solution {
    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
        int[] path = new int[triangle.size()];
        
        // init the path sum as the values at the bottom of the triangle
        for(int i=0; i<triangle.size(); i++) path[i]=triangle.get(triangle.size()-1).get(i);
        
        // calculate the path level by level upward
        for(int i=triangle.size()-2; i>=0; i--){
            for(int j=0; j<=i; j++){// for each element in current level
                // sum of current path = current value + the smaller adjacent numbers from previous level
                path[j] = triangle.get(i).get(j) + Math.min(path[j], path[j+1]);
            }
        }
        return path[0]; 
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值