LeetCode Pascal's Triangle
Problem Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return 没记错的话,这个应该叫杨辉三角型。很简单的题 P...
Problem
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]
]没记错的话,这个应该叫杨辉三角型。很简单的题
Python 实现
'''
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]
]
'''
# author li.hzh
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
last_row = [1]
result = [last_row]
for row in range(2, numRows + 1):
cur_row = [last_row[0]]
for i in range(1, len(last_row)):
cur_row.append(last_row[i] + last_row[i - 1])
cur_row.append(last_row[len(last_row) - 1])
last_row = cur_row
result.append(cur_row)
return result
分析
没什么可分析的,利用上一层计算出下一层的值即可以。
看完题解,马上用 240 关实战检验掌握度
覆盖 GESP 1~8 级考纲心法、CSP-J 双栏阅读程序、错题动态变式推演与 90/120 分钟全真模考。
配套题解代码归档于 yummy-code 仓库,完整知识点索引见 GESP Wiki。
同专栏相关推荐
LeetCode Minimum Depth of Binary Tree
Problem Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root nod...
LeetCode Path Sum
Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path...
LeetCode Path Sum II
Problem Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the b...
OneCoder
始于 2012持续记录 C++ GESP/CSP 信奥算法、Java 服务端架构与 Python 工程实战。官方唯一域名:coderli.com