【Leetcode】Pascal's Triangle (Pascal)

来源:互联网 发布:总量控制 结构优化 编辑:程序博客网 时间:2024/04/28 02:14

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]]
这道题先找规律,第一行开始首字母一定是1,第二行开始首字母和尾字母一定是1,第三行开始中间的数一定等于上一行前两个数的加和

对于第一行首字母一定是1,只需要用一个临时list在循环的开始阶段add1就可以了

ArrayList<Integer> temp = new ArrayList<Integer>();temp.add(1);
对于第二行首字母和尾字母一定是1,只要判断是否是大于第一行就OK了

if (i > 0) {temp.add(1);}
对于第三行开始 直接循环搞定 第i行需要添加的数=result [i-1] [j] + result [i-1] [j+1]

for (int j = 0; j < result.get(i - 1).size() - 1; j++)temp.add(result.get(i - 1).get(j)+ result.get(i - 1).get(j + 1));

最后完整代码如下

public ArrayList<ArrayList<Integer>> generate(int numRows) {ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();for (int i = 0; i < numRows; i++) {ArrayList<Integer> temp = new ArrayList<Integer>();temp.add(1);if (i > 0) {for (int j = 0; j < result.get(i - 1).size() - 1; j++)temp.add(result.get(i - 1).get(j)+ result.get(i - 1).get(j + 1));temp.add(1);}result.add(temp);}return result;}





0 0
原创粉丝点击