[LeetCode] Pascal's Triangle

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、题型分类:

2、思路:先加上1,中间的根据上一层的结果计算,最后加上1

3、时间复杂度:O(n^2)

4、代码:

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> list=new ArrayList<List<Integer>>();
        //special
        if(numRows<=0) return list;
        //general
        List<Integer> tempList=new ArrayList<Integer>();
        tempList.add(1);
        list.add(tempList);
        for(int i=1;i<numRows;i++)
        {
            tempList=new ArrayList<Integer>();
            List<Integer> ts=list.get(i-1);
            tempList.add(1);   //0
            for(int j=1;j<ts.size();j++)
            {
                tempList.add(ts.get(j-1).intValue()+ts.get(j).intValue());
            }
            tempList.add(1);   //ts.size()
            list.add(tempList);
        }
        return list;
    }
}

5、优化:

6、扩展:

原文地址:https://www.cnblogs.com/maydow/p/4644921.html