Java for LeetCode 118 Pascal's Triangle

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

解题思路:

观察法,JAVA实现如下:

    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
		if(numRows<=0)
			return list;
		List<Integer> alist=new ArrayList<Integer>();
		alist.add(1);
		list.add(new ArrayList<Integer>(alist));
		for(int i=2;i<=numRows;i++){
			List<Integer> alist2=new ArrayList<Integer>();
			alist2.add(1);
			for(int j=1;j<i-1;j++)
				alist2.add(alist.get(j-1)+alist.get(j));
			alist2.add(1);
			alist=alist2;
			list.add(new ArrayList<Integer>(alist));
		}
		return list;
    }

 

posted @ 2015-05-24 16:50  TonyLuis  阅读(201)  评论(0编辑  收藏  举报