Given n
pairs of parentheses, write a function to generate all combinations of well-formed (valid) parentheses.
Input: n = 3
Output:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
n
?
n
can be from 0 to any reasonable integer. For interview purposes, constraints would be practical (e.g., 0 ≤ n ≤ 8).n
?
n
is always a valid, non-negative integer for the sake of this problem.The goal is to generate all possible valid combinations of n
pairs of parentheses. This can be efficiently achieved using a recursive backtracking approach:
(
if it would not exceed n
.)
if it would not create an imbalance in parentheses.n
pairs, add it to the result list.def generateParenthesis(n):
def backtrack(current, open_count, close_count):
if len(current) == 2 * n:
result.append("".join(current))
return
if open_count < n:
current.append('(')
backtrack(current, open_count + 1, close_count)
current.pop()
if close_count < open_count:
current.append(')')
backtrack(current, open_count, close_count + 1)
current.pop()
result = []
backtrack([], 0, 0)
return result
# Example usage
print(generateParenthesis(3))
The time complexity of this problem is O(4^n / sqrt(n))
. This comes from the fact that we’re generating all combinations of balanced parentheses, which is a well-known problem with this complexity.
The number of valid parentheses sequences is the n-th Catalan number
, which is approximately O(4^n / sqrt(n))
. This complexity arises from the possible sequences we generate and prune during our recursive backtracking solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?