Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
<strong>Input:</strong> 5 <strong>Output:</strong> [ [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的版本应该可以写出来的。