Generate Parentheses

Generate all well-formed parentheses combinations of length 2n — DFS with open/close counters.

Medium
Time O(4^n / sqrt(n)) Space O(n)
LeetCode
3 min read
subsets backtracking

Problem#

Return all well-formed parentheses strings of length 2n.

Examples#

  • n = 3["((()))","(()())","(())()","()(())","()()()"]

Constraints#

  • 1 <= n <= 8.

Approach#

DFS counting opens and closes used. At each step, branch on adding ( if open < n, and ) if close < open. Both constraints maintain well-formedness.

Solution#

Generate Parentheses
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> out;
string path;
function<void(int,int)> dfs = [&](int open, int close){
if ((int)path.size() == 2 * n) { out.push_back(path); return; }
if (open < n) {
path.push_back('(');
dfs(open + 1, close);
path.pop_back();
}
if (close < open) {
path.push_back(')');
dfs(open, close + 1);
path.pop_back();
}
};
dfs(0, 0);
return out;
}
};

Editorial#

Building incrementally with the invariant close <= open precludes ever creating a malformed string — no pruning, no validation phase. The total count is the n-th Catalan number, ≈ 4^n / sqrt(n).

Complexity#

  • Time: O(4^n / sqrt(n)) (Catalan).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.