给定一个非负整数 numRows,生成杨辉三角的前 numRows 行(第一个我写的,我越优化,效率越低,懵逼)
class Solution(object):
def generate1(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
temp_list = [1 for _ in range(numRows)]
ret_list = []
for i in range(0, numRows):
if i < 2:
ret_list.append(temp_list[:i+1])
continue
pre_value = 1
for j in range(1, i):
cur_value = temp_list[j]
temp_value = pre_value + cur_value
pre_value = cur_value
temp_list[j] = temp_value
ret_list.append(temp_list[:i+1])
return ret_list
def generate2(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
angleArr = []
for index in range(0, numRows):
arr = []
for j in range(index + 1):
if j == 0 or j == index:
arr.append(1)
else:
newItem = angleArr[index - 1][j - 1] + angleArr[index - 1][j]
arr.append(newItem)
angleArr.append(arr)
return angleArr
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
result = []
for i in range(numRows):
now = [1]*(i+1)
if i >= 2:
for n in range(1,i):
now[n] = pre[n-1]+pre[n]
result += [now]
pre = now
return result
if __name__ == '__main__':
s1 = Solution()
n = 7
root = s1.generate(n)
print(root)