您的位置:首页 > 其它

LeetCode——Pascal's Triangle

2014-09-24 16:06 399 查看
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)

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: