Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Generate well-formed parentheses

Produce all combinations of n pairs of well-formed parentheses using recursion and backtracking.

Python practice13 minRecursion & BacktrackingIntermediateLast updated March 27, 2026

Problem statement

Given n pairs of parentheses, generate all combinations of well-formed parentheses. Use recursion/backtracking to explore placement of '(' and ')' while preserving validity (never place more ')' than '(' at any prefix). Return the combinations as a list of strings in the order produced by standard backtracking (always try to place '(' before ')').

Task

Implement a backtracking generator that returns all valid parentheses strings for n pairs, ensuring deterministic ordering.

Examples

Example - n = 3

Input

3

Output

['((()))', '(()())', '(())()', '()(())', '()()()']

All 5 valid combinations for 3 pairs.

Input format

A single integer n (number of pairs).

Output format

A list of strings representing all valid parentheses combinations.

Constraints

0 <= n <= 8. Return combinations in the order produced by backtracking that always attempts '(' before ')'.

Samples

Sample 1

Input

2

Output

['(())', '()()']

Two valid combinations for 2 pairs.