Pascal's Triangle

来源:互联网 发布:淘宝天猫积分怎么兑换 编辑:程序博客网 时间:2024/05/18 22:16

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)


前两天和别人讨论的时候有人说这个杨辉三角是DP的启蒙题,也算吧。其实就和斐波那契数列差不多。认真观察的话就可以知道推导式很简单

f(i, j) = f(i - 1, j - 1) + f(i - 1, j) 每一层的长度是当前的层数i。直接给出代码吧。

    public List<List<Integer>> generate(int numRows) {        Integer[] cur_list = new Integer[1], prev_list = null;        List<List<Integer>> res = new LinkedList<List<Integer>>();        cur_list[0] = 1;        while(numRows > 0){            res.add(Arrays.asList(cur_list));            prev_list = cur_list;            numRows--;            if(numRows > 0){                cur_list = new Integer[prev_list.length + 1];                for(int i = 0; i < cur_list.length; i++){                    cur_list[i] = i == cur_list.length - 1 ? 0 : prev_list[i];                    cur_list[i] += i == 0 ? 0 : prev_list[i - 1];                }            }        }        return res;    }


0 0
原创粉丝点击