Python Basics簡単

Generate balanced parentheses

Detailed guide and Python implementation for the 'Generate balanced parentheses' problem.

問題提起

簡単

Write a function generate_parentheses(n) that generates all combinations of n pairs of well-formed (balanced) parentheses. Return the result as a sorted list of strings. A string of parentheses is balanced if every opening '(' has a corresponding closing ')' and they are properly nested.

制約
  • 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?
Consider using Recursion-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

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 リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。