Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1 Output: ["()"]
Constraints:
1 <= n <= 8
This problem asks to generate all valid combinations of n pairs of parentheses. The solutions presented utilize Depth-First Search (DFS) with pruning and a recursive approach.
This solution uses a depth-first search (DFS) approach with pruning to efficiently generate all valid combinations.
Approach:
The core idea is to recursively build parentheses strings. The function dfs(l, r, t)
keeps track of:
l
: the number of left parentheses used so far.r
: the number of right parentheses used so far.t
: the current parentheses string being built.The recursion proceeds as follows:
Base Cases:
l > n
or r > n
or l < r
: The parentheses combination is invalid (more right than left parentheses or exceeding the n
limit). The function returns immediately.l == n
and r == n
: A valid combination is found. It's added to the ans
array, and the function returns.Recursive Steps:
dfs(l + 1, r, t + '(')
: Adds a left parenthesis and recursively calls dfs
.dfs(l, r + 1, t + ')
): Adds a right parenthesis and recursively calls
dfs`.The pruning step (l > n
or r > n
or l < r
) significantly reduces the search space by eliminating invalid combinations early on.
Time Complexity: O(4n / n1.5)
While the apparent branching factor is 2 (adding '(' or ')'), the actual number of valid combinations grows much slower than 22n due to the constraints. The Catalan numbers provide a more precise estimate. The n
factor in the denominator accounts for string building operations in each recursive step.
Space Complexity: O(n)
The space complexity is dominated by the recursion depth, which is at most 2n
(in the worst-case scenario where we add all left parentheses before any right parentheses), and the space used for storing intermediate strings.
This solution is more concise but might be less intuitive. It leverages the observation that all valid parentheses strings of length 2n
can be generated by inserting "()" into all possible positions of valid strings of length 2(n-1)
.
Approach:
n
is 1, return ["()"]
.n - 1
.s
, insert "()" at every possible index i
(0 to s.length
) creating a new string s.slice(0, i) + '()' + s.slice(i)
.Set
to eliminate duplicate strings.Time Complexity: Difficult to precisely characterize but likely super-exponential due to nested loops implicit in the flatMap
operation and the recursive calls. Each recursive call processes an increasing number of strings.
Space Complexity: Similar to the previous solution, the space complexity is dominated by the recursive call stack and storage of intermediate strings.
Code Examples (Python - Solution 1):
def generateParenthesis(n: int) -> List[str]:
ans = []
def backtrack(s='', left=0, right=0):
if len(s) == 2 * n:
ans.append(s)
return
if left < n:
backtrack(s + '(', left + 1, right)
if right < left:
backtrack(s + ')', left, right + 1)
backtrack()
return ans
The Python code above represents a slightly optimized version of Solution 1, directly using backtracking instead of separate functions for clarity. The time and space complexity analysis remains the same. Other languages would follow a similar structure.