题目描述
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
示例:
输入: 5 输出: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
思路
杨辉三角有以下规律:
- 第一列和最后一列的值都是1
- 从第三行开始,第i列的值(除了首尾)都等于上一行的i-1列+i列的和
Java代码实现
public List<List<Integer>> generate(int numRows) { List<List<Integer>> res = new ArrayList<>(); List<Integer> cur = null; for (int i = 0; i < numRows; i++) { cur = new ArrayList<>(); if(i == 0){ cur.add(1); } else{ cur.add(1); List<Integer> last = res.get(i-1); for(int j=1;j<i;j++){ cur.add(last.get(j)+last.get(j-1)); } cur.add(1); } res.add(cur); } return res; }