题目
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) {
}
}
以上给出方法输入参数,完成作答。
题目分析
- 使用双循环,外循环用于每一行,内循环用户每一行的每一个数
- 首尾都是 1 ,直接赋值就行
- 其他位置使用上一行的左右两个数相加和赋值
解答分析
本文只分析本人做题思路,仅供参考,了解一种解题思想,其他各种做题思路请上网查阅。
解答成功:
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:36.2 MB,击败了77% 的Java用户
class Solution {
public List<List<Integer>> generate(int numRows) {
if (numRows == 0) {
return null;
}
List<List<Integer>> outList = new ArrayList<>();
for (int i = 1; i < numRows + 1; i++) {
List<Integer> list = new ArrayList<>();
for (int j = 0; j < i; j++) {
if (j == 0 || j == i - 1) {//首尾都是1
list.add(1);
} else {//其他位置为上面两个位置相加和
int c = outList.get(i - 2).get(j - 1) + outList.get(i - 2).get(j);
list.add(c);
}
}
outList.add(list);
}
return outList;
}
}