每一行的頭和尾元素均初始化為1;
中間元素由上層[i-1][j-1]+[i-1][j]構成;
每行的長度可以預先確定。
class
solution
:def
generate
(self, numrows:
int)
-> list[list[
int]]:
ans =
for i in
range
(numrows)
: row=[0
]*(i+1
)# row = [0 for _ in range(i+1)]
# 已經根據楊輝三角特點確定每行的長度
row[0]
,row[-1
]=1,
1for j in
range(1
,i):
row[j]
= ans[i-1]
[j-1
]+ans[i-1]
[j]
return ans
class
solution
:def
getrow
(self, rowindex:
int)
-> list[
int]
: ans =[1
]*(rowindex+1)
for i in
range
(rowindex+1)
:for j in
range
(i,1,-
1): ans[j-1]
= ans[j-2]
+ ans[j-1]
return ans
leetcode 118 楊輝三角
前言 python刷leetcode題解答目錄索引 正文 給定乙個非負整數 numrows,生成楊輝三角的前 numrows 行。在楊輝三角中,每個數是它左上方和右上方的數的和。示例 輸入 5 輸出 1 1,1 1,2,1 1,3,3,1 1,4,6,4,1 class solution def g...
LeetCode 118 楊輝三角
給定乙個非負整數 numrows,生成楊輝三角的前 numrows 行。在楊輝三角中,每個數是它左上方和右上方的數的和。示例 輸入 5 輸出 1 1,1 1,2,1 1,3,3,1 1,4,6,4,1 這個問題可以使用動態規劃的方法來解決 c class solution for int i 0 i...
LeetCode118楊輝三角
這道題的思路很明確,就是上一行的倆個數加起來等於下一行的乙個數。區別就是實現方式的不同,當然還有其他思路。再就是注意numrows為0的情況以及輸出格式。建立二維向量 vectorans 此時 ans為空。建立一維向量 vector init init.push back 1 ans.push ba...