练习题:杨辉三角
- 题目要求
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
解:
我们用List<List<Integer>>存储杨辉三角。
创建一个空的链表,首先应该判断所给的整数是否为0。如果为0,直接返回空链表,如果不为0,再进行下面的操作。
因为在杨辉三角中,每个数是它左上方和右上方的数的和,且除第一行外,最左最右的数都是1。所以我们先将为第一行的链表添加元素1,然后再进行n-1次循环,循环的最外层各添加一个1。假设当前是循环的第i趟,在循环内嵌套i-1次循环,填充中间的数。当前行的第h个数等于上一行的第h-1个数与第h个数之和。
代码实现(JAVA):
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> a=new ArrayList<List<Integer>>();
if(numRows>0){
a.add(new ArrayList<Integer>());
a.get(0).add(1);
for(int i=1;i<numRows;i++){
List<Integer> b=new ArrayList<Integer>();
b.add(1);
for(int h=0;h<i-1;h++){
b.add((a.get(i-1).get(h))+(a.get(i-1).get(h+1)));
}
b.add(1);
a.add(b);
}
}
return a;
}
题目来源:力扣(LeetCode)