Pascal's Triangle

来源:互联网 发布:cf无后坐力软件 编辑:程序博客网 时间:2024/05/20 14:42

题目

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]]

方法

根据杨辉三角的定义,可以很容易计算的

    public List<List<Integer>> generate(int numRows) {        List<List<Integer>> list = new ArrayList<List<Integer>>();        if (numRows == 0) {        return list;        }    List<Integer> subListOne = new ArrayList<Integer>();    subListOne.add(1);    list.add(subListOne);            if (numRows == 1) {                return list;        }            List<Integer> subListTwo = new ArrayList<Integer>();    subListTwo.add(1);    subListTwo.add(1);    list.add(subListTwo);        if (numRows == 2) {        return list;        }                for (int i = 2; i < numRows; i++) {        List<Integer> pre = list.get(i - 1);        List<Integer> cur = new ArrayList<Integer>();        cur.add(1);        int len = pre.size();        for (int j = 1 ; j < len; j++) {        cur.add(pre.get(j - 1) + pre.get(j));        }        cur.add(1);        list.add(cur);        }        return list;    }



0 0