数组找规律
难度简单
题目描述
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
解题思路
找规律,下面的数组第i个索引的值 = 上面数组第i-1个索引的值 + 上面数组第i个索引的值
Code
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> resultList = new ArrayList<>();
for (int i = 1; i <= numRows; i++) {
List<Integer> rowList = new ArrayList<>();
if (i == 1) {
rowList.add(1);
resultList.add(rowList);
} else {
List<Integer> lastRowList = resultList.get(i - 2);
rowList.add(1);
for (int j = 0; j < lastRowList.size() - 1; j++) {
int num = lastRowList.get(j) + lastRowList.get(j + 1);
rowList.add(num);
}
rowList.add(1);
resultList.add(rowList);
}
}
return resultList;
}