1. 程式人生 > 實用技巧 >118. 楊輝三角 &119. 楊輝三角 II

118. 楊輝三角 &119. 楊輝三角 II

118.

給定一個非負整數numRows,生成楊輝三角的前numRows行。

在楊輝三角中,每個數是它左上方和右上方的數的和。

示例:

輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/pascals-triangle

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        res=[]
        if
numRows==0: return [] for numRow in range(numRows): row=[None for _ in range(numRow+1)] row[0]=row[-1]=1#每行首尾都是1 for i in range(1,len(row)-1): row[i]=res[numRow-1][i-1]+res[numRow-1][i] res.append(row)
return res

119.

給定一個非負索引k,其中 k≤33,返回楊輝三角的第 k 行。

在楊輝三角中,每個數是它左上方和右上方的數的和。

示例:

輸入: 3
輸出: [1,3,3,1]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/pascals-triangle-ii

一開始無腦用118的程式碼,感覺效率不佳,

class Solution:
    def getRow(self, numRows: int) -> List[int]:
        numRows+=1
        res=[]
        
if numRows==0: return [] for numRow in range(numRows): row=[None for _ in range(numRow+1)] row[0]=row[-1]=1 for j in range(1,len(row)-1): row[j]=res[numRow-1][j-1]+res[numRow-1][j] res.append(row) return res[-1]

改了一下

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        rowIndex+=1
        res=[]
        for numRow in range(rowIndex):
            row=[None for _ in range(numRow+1)]
            row[0]=row[-1]=1
            for j in range(1,len(row)-1):
                row[j]=res[numRow-1][j-1]+res[numRow-1][j]
            if numRow==rowIndex-1:
                return row
            res.append(row)
        

提交兩次截然不同