用 Python 编写程序来查找帕斯卡三角形的第 n 行
pythonserver side programmingprogramming更新于 2026/1/12 5:32:17
假设我们有一个数字 n,我们必须找到帕斯卡三角形的第 n 行(0 索引)。我们知道帕斯卡三角形可以按如下方式创建 −
- 在最上面一行,有一个数组 1。
- 后续行是通过将左上方的数字与右上方的数字相加而得到的。
所以几行如下 −

因此,如果输入为 4,则输出将为 [1, 4, 6, 4, 1]
为了解决这个问题,我们将遵循以下步骤 −
- 如果 n 与 0 相同,则
- 返回 [1]
- 如果 n 与 1 相同,则
- 返回 [1,1]
- ls:= 包含 [1,1] 的列表,temp:= 包含 [1,1] 的列表
- 对于范围为 2 到 n+1 的 i,执行
- ls:= temp
- temp:= 包含一个值的列表 = 1
- 对于 i 在 0 到 ls 大小 -1 范围内的情况,执行
- 合并 ls[i]、ls[i+1] 并插入到 temp 的末尾
- 在 temp 的末尾插入 1
- 返回 temp
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, n): if n==0: return [1] if n==1: return [1,1] ls=[1,1] temp=[1,1] for i in range(2,n+1): ls=temp temp=[1] for i in range(len(ls)-1): temp.append(ls[i]+ls[i+1]) temp.append(1) return temp ob = Solution() print(ob.solve(4))
输入
4
输出
[1, 4, 6, 4, 1]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

