[leetcode]Pascal's Triangle

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

算法思路:

迭代:根据当前行,求出下一行

代码如下:

 1 public class Solution {
 2   List<List<Integer>> result = new ArrayList<List<Integer>>();
 3     public List<List<Integer>> generate(int numRows) {
 4         if(numRows <= 0) return result;
 5         List<Integer> list = new ArrayList<Integer>();
 6         list.add(1);
 7         for(int i = 0; i < numRows; i++){
 8             result.add(new ArrayList<Integer>(list));
 9             list = getNextRow(list);
10         }
11         return result;
12     }
13     private List<Integer> getNextRow(List<Integer> list){
14         List<Integer> l = new ArrayList<Integer>();
15         l.add(1);
16         for(int i = 1 ; i < list.size(); l.add(list.get(i) + list.get(i - 1)),i++);
17         l.add(1);
18         return l;
19     }
20 }

posted on 2014-07-22 00:35  喵星人与汪星人  阅读(413)  评论(0编辑  收藏  举报