Python Nozioni di baseFacile

Genera parentesi bilanciate

Guida dettagliata e implementazione Python per il problema 'Genera parentesi bilanciate'.

Dichiarazione del problema

Facile

Scrivi una funzione generate_parentheses(n) che generi tutte le combinazioni di n coppie di parentesi ben formate (bilanciate). Restituisce il risultato come un elenco ordinato di stringhe. Una stringa di parentesi è bilanciata se ogni apertura '(' ha una chiusura ')' corrispondente e se sono annidate correttamente.

Vincoli
  • 1 <= n <= 8

Esempi

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?
Prendi in considerazione l'utilizzo di strutture dati specifiche della ricorsione come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

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

Apri nell'editor
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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.