【LeeCode 中等 数学 python3】119. 杨辉三角 II

2022-08-01,,,,

想要看更加舒服的排版、更加准时的推送
关注公众号“不太灵光的程序员”
每日八点有干货推送,微信随时解答你的疑问

119. 杨辉三角 II python3

简单 数学

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。

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

示例:

输入: 3
输出: [1,3,3,1]
进阶:

你可以优化你的算法到 O(k) 空间复杂度吗?

from typing import List


# 执行用时:40 ms, 在所有 Python3 提交中击败了72.13%的用户
# 内存消耗:13.6 MB, 在所有 Python3 提交中击败了11.11%的用户
class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        # 根据组合数公式C(n,i)=n!/(i!*(n-i)!)直接由C(n,i)算C(n,i+1),后者是前者的(n-i)/(i+1)倍
        if rowIndex < 0:
            return []
        ans = [1] * (rowIndex + 1)
        for i in range(rowIndex):
            ans[i + 1] = ans[i] * (rowIndex - i) // (i + 1)
        return ans


s = Solution()
ret = s.getRow(0)
print(ret)

s = Solution()
ret = s.getRow(1)
print(ret)

s = Solution()
ret = s.getRow(5)
print(ret)

本文地址:https://blog.csdn.net/qq_23934063/article/details/107583112

《【LeeCode 中等 数学 python3】119. 杨辉三角 II.doc》

下载本文的Word格式文档,以方便收藏与打印。