Python程式:查詢帕斯卡三角形的第n行


假設我們有一個數字n,我們需要找到帕斯卡三角形的第n行(從0開始索引)。眾所周知,帕斯卡三角形可以如下建立:

  • 頂行只有一個數字1。
  • 後續行透過將上一行中與其左上方和右上方的數字相加得到。

因此,前幾行如下:

所以,如果輸入是4,則輸出為[1, 4, 6, 4, 1]

為了解決這個問題,我們將遵循以下步驟:

  • 如果n等於0,則
    • 返回[1]
  • 如果n等於1,則
    • 返回[1,1]
  • ls := 一個包含[1,1]的列表,temp := 一個包含[1,1]的列表
  • 對於範圍從2到n+1的i:
    • ls := temp
    • temp := 一個包含一個值為1的列表
    • 對於範圍從0到ls大小減1的i:
      • 將ls[i]和ls[i+1]合併,並插入到temp的末尾
    • 在temp的末尾插入1
  • 返回temp

讓我們看下面的實現來更好地理解:

示例

線上演示

class Solution:
   def solve(self, n):
      if n==0:
         return [1]
      if n==1:
         return [1,1]
      ls=[1,1]
      temp=[1,1]
      for i in range(2,n+1):
         ls=temp
         temp=[1]
         for i in range(len(ls)-1):
            temp.append(ls[i]+ls[i+1])
         temp.append(1)
      return temp
ob = Solution()
print(ob.solve(4))

輸入

4

輸出

[1, 4, 6, 4, 1]

更新於:2020年10月6日

811 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告