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) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> line;
if(numRows < 1)
return res;
for(int i = 0; i < numRows; i++){
line = new ArrayList<Integer>();
for(int j = 0; j <= i; j++){
if(j == 0)
line.add(1);
else if(j == i)
line.add(1);
else
line.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));
}
res.add(line);
}
return res;
}
}
本文介绍了一种使用Java编程语言生成帕斯卡三角形的方法。通过递增循环,算法可以构建任意层数的帕斯卡三角形,并返回每层元素组成的列表。此算法适用于数学和计算机科学领域。
401

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



