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] ]
The idea here is every row in the triangle is generated based on the row above it. For example, the 3rd row [1, 2, 1] can be generated by going through each item in the row [1, 1], add pre number or 0 for the first item and itself, so it will be 0+1 = 1, 1+1=2, then append 1 in the list.
The code is pretty straightforward.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public List<List<Integer>> generate(int numRows) { | |
List<List<Integer>> list = new ArrayList<>(); | |
for(int i = 1; i<=numRows; i++){ | |
List<Integer> curr = new ArrayList<>(); | |
if(!list.isEmpty()){ | |
int pr = 0; | |
for(int num : list.get(list.size()-1)){ | |
curr.add(num+pr); | |
pr = num; | |
} | |
} | |
curr.add(1); | |
list.add(curr); | |
} | |
return list; | |
} | |
} |
No comments:
Post a Comment