13.1 Triangle

Link: 

My thought: 1 What does adjacent number mean?

e.g. if the triangle is as below. The adjacent numbers means those connected with lines. So the 0 indexed on the top level, is adjacent to the 0 and 1 index in the second level. 



Approach I: from Dai's code. O(1) solution. Why time out?

It uses the triangle itself to save the intermediate sums. 

triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1])

public class Solution {
    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
        int n = triangle.size();
        for(int i = n -2; i>=0; i--){//i is the row index
            for(int j = 0; j < i+1; j++){//j: col index. Each row i has i numbers, so j belongs to[0, i]
                triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i+1).get(j), triangle.get(i+1).get(j+1)));
            }
        }
        return triangle.get(0).get(0);
    }
}

http://blog.csdn.net/linhuanmars/article/details/23230657

这段代码的含义如下图所示:(see Triangle.png)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值