问题描述
给定一个正整数 n,要求输出杨辉三角的前 n 行。题目链接:**点我**
样例输入输出
输入:5
输出:[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
解释:杨辉三角如下

输入:1
输出:[[1]]
问题解法
此题比较简单,直接按照杨辉三角的规则进行输出即可。代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
   | class Solution {     public List<List<Integer>> generate(int numRows) {         List<List<Integer>> result = new ArrayList<>();         for (int i = 0; i < numRows; i++) {             List<Integer> items = new ArrayList<>();             items.add(1);             for (int j = 1; j < i + 1; j++) {                 if (j == i) {                     items.add(1);                 } else {                     List<Integer> prev = result.get(i - 1);                     int num = prev.get(j - 1) + prev.get(j);                     items.add(num);                 }             }             result.add(items);         }                  return result;     } }
  |