118. 杨辉三角 - 力扣(LeetCode) (leetcode-cn.com)

难度:简单
题目描述:给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。

Java刷题随笔---118.杨辉三角 - 图1

分析

  1. 杨辉三角近似看成如下所示的例图:
  2. *
  3. * *
  4. * * *
  5. 所以杨辉三角可以表示为:
  6. 1
  7. 1 1
  8. 1 2 1
  9. 设置两个指针一个为行指针(row),一个为列指针(column
  10. 杨辉三角中的元素可以分为两种情况:
  11. 1- column==0column==row时,值为1
  12. 2- 当为其他情况时,array[row][column] = array[row-1][column-1] + array[row-1][column]

解题

class Solution {
        public List<List<Integer>> generate(int numRows) {

            List<List<Integer>> result = new ArrayList<>();

            for (int i = 0; i < numRows; i++) {
                List<Integer> currentList = new ArrayList<>();
                for (int j = 0; j <= i; j++) {
                    if (i == j || j == 0) {
                        currentList.add(1);
                    } else {
                        currentList.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j));
                    }
                }
                result.add(currentList);
            }

            return result;
        }
    }