Generate Parentheses
Medium
Topics
Given n pairs of parentheses, return all combinations of well-formed parentheses, in any order.
Example 1
Every well-formed string of 3 pairs. The two rules that generate exactly these and nothing else: open a bracket while fewer than 3 are open, and close one only while closes trail opens. That prunes invalid prefixes instead of filtering at the end. There are 5.
Each chip is one valid output string.
Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2
Input: n = 1 Output: ["()"]
Constraints
- 1 <= n <= 8
Editorial — intuition, approach, complexity and pitfalls
Intuition
Build the string one character at a time. You may add "(" while you still have opens left, and ")" only while it would not exceed the number of opens placed — this guarantees validity by construction.
Approach
- DFS carrying counts of open and close brackets used.
- Add "(" if open < n; add ")" if close < open.
- When the string reaches length 2n it is a valid answer.
Dry Run
n = 3. Two counters, and the only two rules are "never open more than n" and
"never close more than you have opened".
"" op 0 cl 0 may open
"(" op 1 cl 0 may open, may close
"((" op 2 cl 0 may open, may close
"(((" op 3 cl 0 open is exhausted, may only close
"((()" -> "((())" -> "((()))" complete
"(()" op 2 cl 1 may open, may close
"(()(" -> "(()()" -> "(()())" complete
"(())" -> "(())(" -> "(())()" complete
"()" op 1 cl 1 may open
"()(" -> "()((" -> "()(()" -> "()(())" complete
"()()" -> "()()(" -> "()()()" complete
answer ((())) | (()()) | (())() | ()(()) | ()()()
No validity check is ever run on a finished string, and that is the point. The two
guards make it impossible to construct an invalid prefix, so every leaf at length
2n is valid by construction -- which is why this generates the 5 Catalan strings
rather than filtering 2^6 = 64 candidates.
The close guard is `cl < op`, not `cl < n`. Those differ the moment a string has
more closes than opens so far. Using `cl < n` for n = 2 produces
(()) ()() ())( )(() )()( ))(( -- six strings, of which only the first two are
balanced.Complexity
- Time — O(4^n / sqrt(n)): the count of valid strings is the nth Catalan number.
- Space — O(n): recursion depth.
Common Pitfalls
- Only close when close < open, or you produce invalid strings like ")(".
Full Solution — all languages
class Solution:
def generateParenthesis(self, n):
res=[]
def dfs(cur,op,cl):
if len(cur)==2*n: res.append(cur); return
if op<n: dfs(cur+'(',op+1,cl)
if cl<op: dfs(cur+')',op,cl+1)
dfs('',0,0)
return resimport java.util.*;
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res=new ArrayList<>();
dfs("",0,0,n,res);
return res;
}
void dfs(String cur,int op,int cl,int n,List<String> res) {
if(cur.length()==2*n) {
res.add(cur);
return;
}
if(op<n)dfs(cur+"(",op+1,cl,n,res);
if(cl<op)dfs(cur+")",op,cl+1,n,res);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<string> generateParenthesis(int n) {
vector<string> res;
function<void(string,int,int)> dfs=[&](string cur,int op,int cl) {
if((int)cur.size()==2*n) {
res.push_back(cur);
return;
}
if(op<n)dfs(cur+"(",op+1,cl);
if(cl<op)dfs(cur+")",op,cl+1);
};
dfs("",0,0);
return res;
}
};/**
* @param {number} n
* @return {string[]}
*/ var generateParenthesis = function(n) {
const res=[];
function dfs(cur,op,cl) {
if(cur.length===2*n) {
res.push(cur);
return;
}
if(op<n)dfs(cur+'(',op+1,cl);
if(cl<op)dfs(cur+')',op,cl+1);
}
dfs('',0,0);
return res;
};