数组找规律

难度简单

题目描述

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
image.png
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

解题思路

找规律,下面的数组第i个索引的值 = 上面数组第i-1个索引的值 + 上面数组第i个索引的值

Code

  1. public List<List<Integer>> generate(int numRows) {
  2. List<List<Integer>> resultList = new ArrayList<>();
  3. for (int i = 1; i <= numRows; i++) {
  4. List<Integer> rowList = new ArrayList<>();
  5. if (i == 1) {
  6. rowList.add(1);
  7. resultList.add(rowList);
  8. } else {
  9. List<Integer> lastRowList = resultList.get(i - 2);
  10. rowList.add(1);
  11. for (int j = 0; j < lastRowList.size() - 1; j++) {
  12. int num = lastRowList.get(j) + lastRowList.get(j + 1);
  13. rowList.add(num);
  14. }
  15. rowList.add(1);
  16. resultList.add(rowList);
  17. }
  18. }
  19. return resultList;
  20. }