目录结构
1.题目
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pascals-triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
前两行特殊处理,后面的行由前一行按照构造规则得出结果。
public class Solution118 {
public List<List<Integer>> generate(int numRows) {
List<Integer> list, pre_list;
List<List<Integer>> result = new ArrayList<>();
if (numRows == 0) {
return result;
}
pre_list = Collections.singletonList(1);
result.add(pre_list);
if (numRows == 1) {
return result;
}
for (int i = 2; i <= numRows; i++) {
list = new ArrayList<>();
list.add(1);
for (int j = 0; j < pre_list.size() - 1; j++) {
list.add(pre_list.get(j) + pre_list.get(j + 1));
}
list.add(1);
result.add(list);
pre_list = list;
}
return result;
}
}
- 时间复杂度:
- 空间复杂度: