首页 > 代码库 > Problem Pascal's Triangle

Problem Pascal's Triangle

Problem Description:

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

 

 

 Solution:
 1     public List<List<Integer>> generate(int numRows) { 2 List<List<Integer>> triangle  = new ArrayList<List<Integer>>(); 3         for (int i = 0; i < numRows; i++) { 4             List<Integer> row = new ArrayList<Integer>(); 5             for (int j = 0; j <= i; j++) { 6                 if (j == 0 || j == i) { 7                     row.add(1); 8                 } else { 9                     row.add(triangle.get(i-1).get(j-1) + triangle.get(i-1).get(j));10                 }11             }12 13             triangle.add(row);14         }15 16         return triangle;17     }