LeetCode题解:Pascal's Triangle

来源:互联网 发布:好搜seo 好搜索引擎 编辑:程序博客网 时间:2024/06/14 22:28

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,
Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

题意是:给定一个正整数numRows代表行数,返回对应行数的 Pascal 三角形。

解决这个问题的办法很简单了,根据 Pascal 三角形的特征计算就可以了。

代码:

public List<List<Integer>> generate(int numRows) {        ArrayList<Integer> row = new ArrayList<Integer>();        List<List<Integer>> allrows = new ArrayList<List<Integer>>();        for(int i = 0;i < numRows;++i){            row.add(0, 1);            for(int j = 1;j < row.size() - 1;++j){                row.set(j, row.get(j) + row.get(j + 1));            }            allrows.add(new ArrayList<Integer>(row));        }        return allrows;    }
0 0
原创粉丝点击