LeetCode——Pascal's Triangle

时间:2024-04-02 08:36:50

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]
] https://oj.leetcode.com/problems/pascals-triangle/ 杨辉三角,先把两遍的值设为1,然后算中间的就是上一层的两个数相加,算当前层的时候,上一层下标一定是从0开始一直加到最后一个。 Python代码
class PascalsTriangle:
def generate(self, numRows):
res = []
for i in range(1, numRows+1):
tem = [0 for x in range(i)]
if i == 1:
tem[0] = 1
# print(tem[0])
res.append(tem)
else:
pos = 0
for j in range(1, i+1):
if j == 1:
tem[0] = 1
elif j == i:
tem[j - 1] = 1
else:
tem[j-1] = res[i-2][pos] + res[i-2][pos+1]
pos += 1
res.append(tem)
return res p = PascalsTriangle()
p.generate(5)