Leetcode 118.杨辉三角
- 杨辉三角
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> L = new ArrayList<List<Integer>>();
List<Integer> l = new ArrayList<Integer>();
if(numRows>0){
l.add(1);
L.add(l);
for(int i = 1; i < numRows;i++){
List<Integer> list = new ArrayList<Integer>();
l = L.get(i-1);
for(int j = 0; j <= i;j++){
if(j == 0||j == i)
list.add(1);
else{
int a = l.get(j-1);
int b = l.get(j);
list.add(a+b);
}
}
L.add(list);
}
}
return L;
}
}
执行结果:
通过
显示详情
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:36 MB, 在所有 Java 提交中击败了99.34% 的用户
本文详细介绍了LeetCode上的第118题——杨辉三角的解决方案。该题要求生成给定行数的杨辉三角,每行的每个元素为其正上方两个元素之和。文章提供了完整的Java代码实现,并通过了平台的测试。

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



