118. Pascal's Triangle

来源:互联网 发布:淘宝服装女装 编辑:程序博客网 时间:2024/06/07 21:58

杨辉三角

QUESTION

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. ArrayList的元素依旧是ArrayList对象
  2. 注意类型转换
  3. 集合的插入和获取操作
public class Solution {    public List<List<Integer>> generate(int numRows) {        //List<List<Integer>> lists = new ArrayList<ArrayList<Integer>>();        List<List<Integer>> lists = new ArrayList<>();        if(numRows <= 0) return lists;        List<Integer> list1 = new ArrayList<Integer>();        list1.add(1);        lists.add(list1);        List<Integer> oldList = list1;        for(int i = 2; i <= numRows; i++) {            List<Integer> list = new ArrayList<Integer>();            list.add(1);            list.add(1);            for(int j = 1; j < i-1; j++) {                list.add(j,oldList.get(j - 1) + oldList.get(j));            }            oldList = list;            lists.add(list);        }        return lists;    }}
0 0
原创粉丝点击