118. Pascal’s Triangle(帕斯卡三角形)

3,372次阅读
没有评论

共计 564 个字符,预计需要花费 2 分钟才能阅读完成。

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

118. Pascal's Triangle(帕斯卡三角形)
In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

解法

class Solution:
    def generate(self, numRows):
        result = []
        for num in range(numRows):

            if num == 0:
                result.append([1])
            elif num == 1:
                result.append([1, 1])
            else:
                tmp = []
                tmp.append(1)
                for _pre in range(num - 1):
                    tmp.append(result[num - 1][_pre] + result[num - 1][_pre + 1])
                tmp.append(1)
                result.append(tmp)
        return result

说明:

第一行与第二行直接通过返回相应的数据
从第三行开始使用上一行相邻元素的相加来得到,但是列表收尾都是1
只要这个逻辑理清楚,最native的版本应该可以写出来的。

正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2019-04-04发表,共计564字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码