An interactive visualization of DFS/backtracking to generate all valid parentheses combinations. Watch the decision tree build as the algorithm chooses to add '(' or ')' at each step.
DFS LeetCode 22 โ Mediumn pairs of parentheses, write a function to generate all combinations of well-formed parentheses.n = 3, the result is:["((()))", "(()())", "(())()", "()(())", "()()()"]
fun generateParenthesis(n: Int): List<String> { val result = mutableListOf<String>() fun dfs(openCount: Int, closeCount: Int, current: String) { if (current.length == 2 * n) { result.add(current) return } if (openCount < n) { dfs(openCount + 1, closeCount, current + "(") } if (closeCount < openCount) { dfs(openCount, closeCount + 1, current + ")") } } dfs(0, 0, "") return result}
At each position, we can add ( if open_count < n,
or ) if close_count < open_count. This ensures we
never have more closing than opening parentheses at any point in the string,
which is exactly the condition for well-formed parentheses.
( or a closing paren ).( if we haven't used all n opening parens yet (open_count < n).) if doing so won't create an invalid prefix (close_count < open_count).2n, it's a valid combination โ add it to the result.
The number of valid parentheses combinations is the n-th Catalan number,
which is C(2n, n) / (n+1), bounded by O(4n / n3/2).
Each combination takes O(n) to construct, giving O(4n / √n) total work.
The recursion depth (and thus space for the call stack) is O(n).