您的位置:首页 > 编程语言 > Python开发

leetcode 【 Pascal's Triangle 】python 实现

2015-01-16 23:15 393 查看
题目

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]
]

代码:oj测试通过 Runtime: 46 ms

class Solution:
# @return a list of lists of integers
def generate(self, numRows):
if numRows < 1:
return []
pascal = []
first_row = [1]
pascal.append(first_row)
for i in range(1,numRows):
tmp = []
tmp.append(1)
for j in range(len(pascal[i-1])):
if j == len(pascal[i-1])-1:
tmp.append(1)
else:
tmp.append(pascal[i-1][j] + pascal[i-1][j+1])
pascal.append(tmp)
return pascal


思路

排除几个special case

然后把pascal写成如下的形式,比较容易写代码:

[1]

[1,1]

[1,2,1]

[1,3,3,1]

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