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

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

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

Leetcode118.gif

分析

杨辉三角近似看成如下所示的例图:
*
* *
* * *
所以杨辉三角可以表示为:
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;
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容