AAlgoLoopSpaced repetition for LeetCode
MEDIUMBacktrackingLeetCode ↗

Generate Parentheses

The key idea

Build the string one character at a time. You may add ( only while the count of opens is below n, and you may add ) only while the count of closes is still below the count of opens. Those two rules keep every prefix valid, so you never waste time on a string that can fail.

Problem

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

A string of parentheses is well-formed when every ( has a matching ) that comes after it, and the pairs are properly nested. Return the answers in any order, but each combination must use exactly n opening and n closing parentheses.

Constraints

Examples

Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]
Input: n = 1 Output: ["()"]

Complexity

Time: O(4^n / sqrt(n)) Space: O(4^n / sqrt(n))

See the full solution

410310
Step-by-step visualization
Start free →

More Backtracking problems