力扣 118. 杨辉三角

本文介绍了如何使用Python解决力扣中的杨辉三角问题。通过迭代法详细解释了代码实现,并提供了一行解法,其中利用数学知识计算组合数Cnk。代码执行效率较高,击败了一定比例的用户。
摘要由CSDN通过智能技术生成

图片

题目描述

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

杨辉三角

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pascals-triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


迭代法

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        if numRows < 1:
            return []
        res = [[1]]
        if numRows == 1:
            return res
        res.append([1, 1])
        if numRows == 2:
            return res
        for i in range(3, numRows + 1):
            res.append([1, *[res[-1][i] + res[-1][i + 1] for i in range(len(res[-1]) - 1)], 1])
        return res

执行结果:通过
执行用时:48 ms, 在所有 Python3 提交中击败了13.88% 的用户
内存消耗:13.6 MB, 在所有 Python3 提交中击败了5.21% 的用户


一行解

参考了 typingMonkey 的题解

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        return [[math.comb(i, j) for j in range(i + 1)] for i in range(numRows)]

执行结果:通过
执行用时:36 ms, 在所有 Python3 提交中击败了80.99% 的用户
内存消耗:13.6 MB, 在所有 Python3 提交中击败了7.03% 的用户

这里用到了数学知识以及 math.comb(n, k) 来求组合数,即从 n 个元素中任取 k 个元素,一共有多少种取法。

C n k = n ! k ! × ( n − k ) ! C_n^k = \frac{n!}{k! \times {(n - k)!}} Cnk=k!×(nk)!n!

相关的帮助文档如下:

>>> import math
>>> help(math.comb)
Help on built-in function comb in module math:

comb(n, k, /)
    Number of ways to choose k items from n items without repetition and without order.

    Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
    to zero when k > n.

    Also called the binomial coefficient because it is equivalent
    to the coefficient of k-th term in polynomial expansion of the
    expression (1 + x)**n.

    Raises TypeError if either of the arguments are not integers.
    Raises ValueError if either of the arguments are negative.

顺带说一下,math 模块中,math.perm 是用来求排列数的函数,之前还用到过求可迭代对象连乘的 math.prod

以第 5 行的杨辉三角列表 [1, 4, 6, 4, 1] 为例,它恰好为:

[ C 4 0 , C 4 1 , C 4 2 , C 4 3 , C 4 4 ] [C_4^0, C_4^1, C_4^2, C_4^3, C_4^4] [C40,C41,C42,C43,C44]

所以第 i 行的杨辉三角列表为 C i − 1 j C_{i - 1}^j Ci1j,其中 0 ⩽ j ⩽ i − 1 0 \leqslant j \leqslant i - 1 0ji1


2020.12.06


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值