题目描述
自己解法
运用动态规划思想,当前层下标0、-1
的元素值为1,下标从1
到len(res)-1
的元素中,若下标为i
,其值等于上一层下标[i]、[i-1]
的元素之和,Python实现:
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if not numRows:
return []
else:
ans = []
for i in range(numRows):
res = [1] * (i+1)
if i > 1:
for j in range(1,len(res)-1):
res[j] = ans[i-1][j-1] + ans[i-1][j]
ans.append(res)
return ans
官方解法
官方解法的思路跟我一样,也差不多:
class Solution:
def generate(self, num_rows):
triangle = []
for row_num in range(num_rows):
# The first and last row elements are always 1.
row = [None for _ in range(row_num+1)]
row[0], row[-1] = 1, 1
# Each triangle element is equal to the sum of the elements
# above-and-to-the-left and above-and-to-the-right.
for j in range(1, len(row)-1):
row[j] = triangle[row_num-1][j-1] + triangle[row_num-1][j]
triangle.append(row)
return triangle
题解区
题解区大佬发现发现当前一行只比上一行多了一个元素,最最关键的一点:本行元素等于上一行元素往后错一位再逐个相加,具体参考:
取巧解法
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 0: return []
res = [[1]]
while len(res) < numRows:
newRow = [a+b for a, b in zip([0]+res[-1], res[-1]+[0])]
res.append(newRow)
return res