题目
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
题解
/*
*杨辉三角中,除了第一行,其余每行的值都是上一行的值错开一位数后相加的结果
* 第一行: 1
* 第二行: 1 0
* + 0 1
* ——————————————————
* 1 1
*
* 第三行: 1 1 0
* + 0 1 1
* ————————————————————
* 1 2 1
*
*
*/
public class Test118 {
public List<List<Integer>> generate(int numRows) {
//创建二维数组用于存储杨辉三角
List<List<Integer>> lists = new ArrayList<List<Integer>>();
//当numRows == 0 时,,,返回空的数组
if (numRows == 0){
return lists;
}
//创建第一行数组,,并存入 1,,,将第一行数组存入到lists中
List<Integer> firstList = new ArrayList<>();
firstList.add(1);
lists.add(firstList);
//获取杨辉三角的行数赋值给size,,并比较size与所给值得大小
int size = lists.size();
while(size < numRows){
//创建两个链式表,,,分别在前和后插入 0 进行错位
// LinkedList 底层数据结构是链表,有addFirst()和addSecond()两个方法,,可以直接在表头表尾添加数据
LinkedList<Integer> first = new LinkedList<>();
LinkedList<Integer> second = new LinkedList<>();
first.addFirst(0);
second.addLast(0);
//将当前杨辉三角的最后一行的值添加到两个错位行
for(Integer row: lists.get(size-1)){
first.addLast(row);
second.addFirst(row);
}
//创建新的一行,,并通过first与second相加得到该行数据
List<Integer> newRow = new ArrayList<>();
for (int i = 0;i<first.size();i++){
newRow.add((first.get(i) + second.get(i)));
}
//为杨辉三角加入最新行,,杨辉三角的size加一
lists.add(newRow);
size++;
}
return lists;
}