Question
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] ]
Stats
Frequency | 1 |
Difficulty | 2 |
Adjusted Difficulty | |
Time to use | -------- |
Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)
Analysis
This is a math question.
Below is my code.
Code
public ArrayList<ArrayList<Integer>> generate(int numRows) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
if (numRows == 0)
return ans;
for (int i = 0; i < numRows; i++){
ArrayList<Integer> list = new ArrayList<Integer>();
for (int j = 0; j <= i; j++){
if (j == 0 || j == i){
list.add(1);
} else {
list.add(ans.get(i-1).get(j-1) + ans.get(i-1).get(j));
}
}
ans.add(list);
}
return ans;
}