Generate Parentheses
Imagine you are designing a code editor that automatically suggests all valid ways to complete a partially typed expression with parentheses. Generating all valid combinations of parentheses helps ensure syntactically correct expressions.
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses strings. Return the list of all valid strings.
1 ≤ n ≤ 8def generateParenthesis(n: int) -> list:public List<String> generateParenthesis(int n)vector<string> generateParenthesis(int n)function generateParenthesis(n)def generateParenthesis(n):
# Write your solution here
passclass Solution {
public List<String> generateParenthesis(int n) {
// Write your solution here
return new ArrayList<>();
}
}#include <vector>
#include <string>
using namespace std;
vector<string> generateParenthesis(int n) {
// Write your solution here
return {};
}function generateParenthesis(n) {
// Write your solution here
}((()))(()())(())()()(())Missing last valid sequence '()()()' due to greedy always adding '(' first.✅ In backtracking, explore adding ')' when close < open, not just '(' when open < n.()()()()()((()))Output includes invalid sequences with more than n pairs due to reusing pairs multiple times.✅ Limit open and close counts to n; do not reuse pairs beyond n.((()))(()())(())()()(())()()()()Including sequences shorter than 2*n length due to incorrect recursion termination.✅ Add sequences only when length == 2*n.()Non-empty output for n=0 due to missing base case handling.✅ Return empty list immediately if n=0.{"n":3}["((()))","(()())","(())()","()(())","()()()"]All valid combinations of 3 pairs of parentheses are generated without duplicates.
{"n":2}["(())","()()"]All valid combinations of 2 pairs of parentheses are generated without duplicates.
{"n":0}[""]No pairs means no parentheses; output is empty list.
{"n":1}["()"]Single pair of parentheses has only one valid combination.
{"n":8}nullLargest input within constraints; must complete efficiently without timeout.
{"n":3}["((()))","(()())","(())()","()(())","()()()"]Tests greedy approach trap: adding '(' whenever possible leads to missing valid sequences.
{"n":2}["(())","()()"]Tests confusion between 0/1 knapsack style and this problem: cannot reuse parentheses pairs multiple times.
{"n":4}["(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"]Tests off-by-one errors in recursion depth or counts leading to missing or extra sequences.
{"n":8}nulln=8 tests performance of backtracking with pruning; brute force O(2^(2n)*n) will time out.
