[LeetCode]题解(python):118 Pascal's Triangle

时间:2022-10-26 07:35:50

题目来源


https://leetcode.com/problems/pascals-triangle/

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

题意分析


Input:integer

Output:帕斯卡三角

Conditions:帕斯卡三角数值的规律


题目思路


注意帕斯卡三角中,除了首尾,其他值为上一层的两个邻值的和


AC代码(Python)

 class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
ans = []
for i in range(numRows):
this = []
for j in range(i+1):
this.append(1)
if i > 1:
for x in range(i - 1):
this[x+1] = ans[i-1][x] + ans[i-1][x+1]
print this
ans.append(this)
return ans