LeetCode

这道题是生成杨辉三角,看了下杨辉三角的性质,就可以解决了。

下面是AC代码:

 1 /**
 2      * Given numRows, generate the first numRows of Pascal's triangle.
 3      * @param numRows
 4      * @return
 5      */
 6     public ArrayList<ArrayList<Integer>> generate(int numRows){
 7         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 8         if(numRows<=0)
 9             return result;
10         ArrayList<Integer> row1 = new ArrayList<Integer>();
11         row1.add(1);
12         result.add(row1);
13         if(numRows == 1)
14         {
15             return result;
16         }
17         ArrayList<Integer> row2 = new ArrayList<Integer>();
18         row2.add(1);
19         row2.add(1);
20         result.add(row2);
21         if(numRows == 2){
22             return result;
23         }
24         for(int i=3;i<=numRows;i++){
25             ArrayList<Integer> ls = new ArrayList<Integer>();
26             genOneRow(i,result.get(i-2),ls);
27             result.add(ls);
28         }
29         return result;
30     }
31     /**
32      * 生成第row排的结果
33      * @param row
34      * @param last
35      * @param curr
36      */
37     private void genOneRow(int row,ArrayList<Integer> last, ArrayList<Integer> curr){
38         curr.add(1);
39         for(int i=0;i<last.size()-1;i++){
40             curr.add(last.get(i)+last.get(i+1));
41         }
42         curr.add(1);
43     }
44     
有问题可以和我联系,bettyting2010#163 dot com
原文地址:https://www.cnblogs.com/echoht/p/3703021.html