Java刷题随笔---118--杨辉三角

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

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

分析

杨辉三角近似看成如下所示的例图:
*
* *
* * *
所以杨辉三角可以表示为:
1
1 1
1 2 1
设置两个指针一个为行指针(row),一个为列指针(column)
杨辉三角中的元素可以分为两种情况:
1- 当column==0或column==row时,值为1
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;
        }
    }
posted on 2021-12-20 15:13  PancrasDuan  阅读(31)  评论(0)    收藏  举报