[LeetCode]Pascal's Triangle

来源:互联网 发布:php 下载pdf文件 编辑:程序博客网 时间:2024/06/08 13:55

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

本题难度Easy。

【复杂度】
时间 O(N^2) 空间 O(N)

【思路】
本题就是求杨辉三角。除了第一行单独生成以外,其他的都是按照上一行生成本行的元素(除了第一个和最后一个都是1,单独加入)。

【代码】

public class Solution {    public List<List<Integer>> generate(int numRows) {        //require        List<List<Integer>> ans=new LinkedList<>();        if(numRows<1)            return ans;        List<Integer> pre=new LinkedList<>();        pre.add(1);        ans.add(pre);        //invariant        for(int i=2;i<=numRows;i++){            List<Integer> list=new LinkedList<>();            list.add(1);            for(int j=1;j<i-1;j++)                list.add(pre.get(j-1)+pre.get(j));            list.add(1);            ans.add(list);            pre=list;        }        //ensure        return ans;    }}
0 0