Title: Also known as "Yang Hui's Triangle"
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Idea: use dynamic programming. First, the number of row 0 is 1; second, the first and last of each row are 1; finally, the other values are the values to the left of his previous row + the right of the previous row (bordering it).
How to do it: Think of the triangle as a big list, and store each row in the big list as a list of rows.
1 class Solution { 2 public List<List<Integer>> generate( int numRows) { 3 List<List<Integer>> triangle = new ArrayList<List<Integer>> ();//Store the entire triangle, where each row is also A list of integers. 4 if (numRows == 0 ){//When 0 rows are required, output an empty list; 5 return triangle; 6 } 7 triangle.add( new ArrayList<> ());//The first row is always 1 8 triangle.get(0).add(1 ); 9 for ( int numRow = 1; numRow < numRows; numRow ++ ){ 10 List<Integer> row = new ArrayList<> (); 11 List<Integer> prevrow = triangle.get(numRow-1 ); 12 row.add(1 );//The first of each row=1 13 for ( int j =1; j < numRow ; j++ ){ 14 row.add(prevrow.get(j-1)+ prevrow.get(j));//The middle element is equal to the sum of the left and right of the previous row; 15 } 16 row.add(1 );//The last of each row=1; 17 triangle.add(row); 18 } 19 return triangle; 20 } 21 }