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]
]
public class Solution {
public ArrayList<ArrayList<Integer>> generate(int numRows) {
ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
if (numRows <= 0) return listAll;
for (int i = 0; i < numRows; i++) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (i == 0) {
list.add(1);
} else {
ArrayList<Integer> prevList = listAll.get(i - 1);
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
list.add(1);
} else {
list.add(prevList.get(j-1) + prevList.get(j));
}
}
}
listAll.add(list);
}
return listAll;
}
}
本文介绍了一个用于生成给定行数的帕斯卡三角形的算法,并提供了具体的代码实现。通过循环和列表操作,该算法可以高效地生成所需的三角形结构。
7891

被折叠的 条评论
为什么被折叠?



