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

[解题思路]

第三行开始,每行除边界元素外,每个元素ai都是由ai-1 + ai构成

 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> generate(int numRows) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 6         if(numRows <= 0){
 7             return result;
 8         }
 9         // row 1
10         ArrayList<Integer> one = new ArrayList<Integer>();
11         one.add(1);
12         result.add(one);
13         if(numRows == 1){
14             return result;
15         }
16         // row 2
17         ArrayList<Integer> two = new ArrayList<Integer>();
18         two.add(1);
19         two.add(1);
20         result.add(two);
21         if(numRows == 2){
22             return result;
23         }
24         for(int i = 3; i <= numRows; i++){
25             int resultSize = result.size();
26             ArrayList<Integer> last = result.get(resultSize - 1);
27             ArrayList<Integer> cur = new ArrayList<Integer>();
28             for(int j = 1; j <= i; j++){
29                 if(j == 1 || j == i){
30                     cur.add(1);
31                 } else {
32                     int num = last.get(j - 1) + last.get(j - 2);
33                     cur.add(num);
34                 }
35             }
36             result.add(cur);
37         }
38         return result;
39     }
40 }

 

posted @ 2013-08-23 11:18  feiling  阅读(435)  评论(0编辑  收藏  举报