Python 基礎知識簡單

帕斯卡三角形的第N行

“帕斯卡三角形第 N 行”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 pascal_row(n),使用遞迴將帕斯卡三角形的第 n 行作為整數列表傳回。行是 0 索引的:第 0 行是 [1],第 1 行是 [1, 1],第 2 行是 [1, 2, 1],等等。每個元素是前一行中位於其正上方的兩個元素的總和。

約束條件
  • 0 <= n <= 30

範例

Example 1
Input
n = 0
Output
[1]
Explanation

The 0th row of Pascal's Triangle is just [1].

Example 2
Input
n = 4
Output
[1, 4, 6, 4, 1]
Explanation

Row 3 is [1,3,3,1]. Row 4: 1, (1+3)=4, (3+3)=6, (3+1)=4, 1.

Example 3
Input
n = 2
Output
[1, 2, 1]
Explanation

Row 1 is [1,1]. Row 2: 1, (1+1)=2, 1.

Need a Hint?
考慮使用特定於遞歸的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。