Python 基礎知識簡單

產生平衡括號

「產生平衡括號」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 generate_parentheses(n) ,產生 n 對格式良好(平衡)括號的所有組合。以字串排序列表的形式傳回結果。如果每個左括號 '(' 都有相應的右括號 ')' 並且它們正確嵌套,則一串括號是平衡的。

約束條件
  • 1 <= n <= 8

範例

Example 1
Input
n = 3
Output
['((()))', '(()())', '(())()', '()(())', '()()()']
Explanation

All 5 valid ways to arrange 3 pairs of parentheses.

Example 2
Input
n = 1
Output
['()']
Explanation

Only one way to arrange 1 pair of parentheses.

Example 3
Input
n = 2
Output
['(())', '()()']
Explanation

Two valid arrangements: nested or sequential.

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 資源

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