Leetcode 118. 杨辉三角

一、题目

题目描述:
Leetcode 118. 杨辉三角_第1张图片

二、思路

解法一:直接按照定义打印出每一行,并依次添加到结果中;
解法二:观察规律可以发现,除一行以外,每一行都可以由上一行通过左右两端分别补一个零的方式错位相加所得:
如第三行的[1, 2, 1]可以由第二行[0, 1, 1]+[1, 1, 0]=[1, 2, 1]所得,每一行以此类推;

三、代码

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
    	# 解法一
        if numRows == 0: return []
        elif numRows == 1: return [[1]]
        res = [[1]]
        pre = [1]
        while len(res) < numRows:
            tmp = []
            for j in range(len(pre)-1):
                tmp.append(pre[j] + pre[j+1])
            pre = [1] + tmp + [1]
            res.append(pre)
        return res
        
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
    	# 解法二
        if numRows == 0: return []
        res = [[1]]
        while len(res) < numRows:
            res.append([a + b for a, b in zip([0]+res[-1], res[-1]+[0])])
        return res

你可能感兴趣的:(编程题)