我正在努力解决问题Pascal's Triangle - LeetCode
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:
Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
我的解决方案:
class Solution:
def __init__(self):
self.res = [[]]
def generate(self, numRows: int) -> 'List[List[int]]':
#base case
if numRows == None: return None
if numRows == 0: return None
pt = []
for i in range(1, numRows+1):
row = [1] * i
pt.append(row)
if numRows <=2: return pt
#recur relations
for i in range(2, numRows): #start from row 3
for j in range(1, len(pt[i])-1):#column,
#logging.debug(f"i:{i}, i-1:{i-1}, j:{j}, j-1:{j-1}")
pt[i][j] = pt[i-1][j-1] + pt[i-1][j]
return pt
很遗憾,没有通过leetcodes的Testcase:
numRows = 0, expected [] but output None.
我曾经想得很透彻,如果numRows为0,就意味着该行不存在,而不是存在一行但元素为零。
numRow == 0 与 numRow = None 相同,区别于 my_salary = 0(免费工作)和 my_salary ==None(无工作)
明确地说,薪水可以是负数,但在我们应该花费数年才能将图片渲染为黑洞的情况下,以当前的技术不能得到负数。
如何理解默认设置numRows = 0
却得到[]
最佳答案
在您的示例中,有一个外部列表包围着所有内部数字列表(行)。这个外部列表将永远存在,即使没有行。它始终是一个包含 numRows
元素的列表,因此如果 numRows == 0
,则它是一个包含 0 个元素的列表。
基本上只需删除开头的两个 if numRows ==
检查,它应该会通过测试用例。
关于python - 生成帕斯卡三角形的极端情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55720992/