【LeetCode】 118. 杨辉三角

题目

题目传送门:传送门(点击此处)
在这里插入图片描述

题解

我的题解

因为第一行和第二行比较特殊,所以我单独存的

class Solution {

    public List<List<Integer>> generate(int numRows) {
        if (numRows == 0) return new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        List<List<Integer>> lists;

        if (numRows == 1) {
            lists = new ArrayList<>();
            list.add(1);
        } else if (numRows == 2) {
            lists = generate(numRows - 1);
            list.add(1);
            list.add(1);
        } else {
            lists = generate(numRows - 1);
            List<Integer> temp = lists.get(numRows - 2);
            list.add(1);
            for (int i = 0; i < numRows - 2; i++) {
                list.add(temp.get(i) + temp.get(i + 1));
            }
            list.add(1);
        }
        lists.add(list);
        return lists;
    }
}

更优雅的方式(这个是python3,不是我写的)

题目的题解有人使用特别优雅的代码写出来了,所以我贴一下:
链接:点击此处

观察一下规律,发现当前一行只比上一行多了一个元素,最最关键的一点:本行元素等于上一行元素往后错一位再逐个相加:
在这里插入图片描述
因此我们只要对最后一行单独处理:最后一行首、尾分别添加一个零然后对应位置求和就可以得到新的一行,思路上比较清晰,占用的时间、空间复杂度也都还挺好<(▰˘◡˘▰)

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        if numRows == 0: return []
        res = [[1]]
        while len(res) < numRows:
            newRow = [a+b for a, b in zip([0]+res[-1], res[-1]+[0])]
            res.append(newRow)      
        return res
发布了151 篇原创文章 · 获赞 148 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq1515312832/article/details/104356495