13.1 Triangle

来源:互联网 发布:淘宝卖家代理怎么发货 编辑:程序博客网 时间:2024/06/08 15:51

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)



0 0
原创粉丝点击