LeetCode OJ 118. Pascal's Triangle

时间:2023-03-08 23:16:18
LeetCode OJ 118. Pascal's Triangle

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

Subscribe to see which companies asked this question

【思路】

这道题目很简单,代码如下:

 public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> Pascal = new ArrayList<>();
if(numRows == 0) return Pascal;
List<Integer> list = new ArrayList<>();
list.add(1);
Pascal.add(list);
if(numRows == 1) return Pascal; for(int i = 1; i < numRows; i++){
list = new ArrayList<>();
list.add(1);
List<Integer> prelist = Pascal.get(i-1);
int prelen = prelist.size();
for(int j = 0; j < prelen - 1; j++){
list.add(prelist.get(j) + prelist.get(j+1));
}
list.add(1);
Pascal.add(list);
}
return Pascal;
}
}