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 <= 8When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
When you need to create all possible combinations of opening and closing parentheses for a given number of pairs, the brute force approach is to write down every single possible combination of the correct length. Once you have generated all of those possibilities, you go through them one by one and throw away any combination that does not make grammatical sense.
Here's how the algorithm would work step-by-step:
def generateParenthesis(pair_count):
total_length = pair_count * 2
# Generate every single permutation of opening and closing characters
def generate_all_combinations(current_string):
if len(current_string) == total_length:
return [current_string]
return generate_all_combinations(current_string + '(') + generate_all_combinations(current_string + ')')
all_possibilities = generate_all_combinations('')
# Verify grammatical correctness by tracking nesting depth balance
def is_combination_valid(candidate):
nesting_balance = 0
for symbol in candidate:
if symbol == '(':
nesting_balance += 1
else:
nesting_balance -= 1
if nesting_balance < 0:
return False
return nesting_balance == 0
valid_combinations = []
# Filter the massive list to retain only grammatically sound strings
for candidate_string in all_possibilities:
if is_combination_valid(candidate_string):
valid_combinations.append(candidate_string)
return valid_combinationsInstead of blindly guessing every possible combination of parentheses, the optimal approach builds valid sequences step by step by making smart choices. It ensures the resulting string is always structurally sound by tracking how many opening and closing symbols are still available to place.
Here's how the algorithm would work step-by-step:
class Solution:
def generateParenthesis(self, pair_count: int) -> list[str]:
valid_combinations = []
def backtrack(current_string, open_count, close_count):
if len(current_string) == pair_count * 2:
valid_combinations.append(current_string)
return
# We can always add an opening parenthesis as long as we have some left.
if open_count < pair_count:
backtrack(current_string + '(', open_count + 1, close_count)
# Closing parentheses can only be added if they do not exceed open ones.
if close_count < open_count:
backtrack(current_string + ')', open_count, close_count + 1)
backtrack('', 0, 0)
# Returning the list guarantees all perfectly balanced combinations are outputted.
return valid_combinations| Case | How to Handle |
|---|---|
| Input n equals zero | The recursive backtracking function should immediately return a list containing a single empty string. |
| Input n equals one | The algorithm builds and returns the only possible valid combination which is a single pair. |
| Maximum expected constraints such as n equals eight | Backtracking naturally scales within acceptable time limits and prevents generating invalid permutations upfront. |
| Deep recursion depth for larger values of n | The call stack depth reaches 2n, which is safely within standard system stack limits for expected constraints. |
| Preventing invalid prefix strings during generation | The algorithm enforces the invariant that close count never exceeds open count at any recursive step. |
| Ensuring all valid combinations are uniquely generated | By strictly branching on available open and close counts, we avoid generating duplicates entirely. |
| Negative values of n | Constraint validation at the entry point should check for non-negative integers and return an empty list. |
| Memory limits due to large output size | Since the total output scales with the Catalan number C_n, memory consumption grows exponentially and must fit within heap limits. |