Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Input: n = 3Output: ["((()))","(()())","(())()","()(())","()()()"]
Solution
Use backtracking to generate all possible combinations of parentheses. Start with an empty string and add a (
if the number of open parentheses is less than n
and add a )
if the number of close parentheses is less than the number of open parentheses. If the length of the current string is equal to n * 2
, add the current string to the result.
Implementation
/** * @param {number} n * @return {string[]} */var generateParenthesis = function (n) { let max = n * 2; const result = []; var backtrack = function (current, open, close) { if (current.length === max) { result.push(current); return; }
if (open < n) { backtrack(current + "(", open + 1, close); }
if (close < open) { backtrack(current + ")", open, close + 1); } }; backtrack("", 0, 0, result); return result;};
function generateParenthesis(n: number): string[] { let max = n * 2; const result: string[] = []; function backtrack(current: string, open: number, close: number) { if (current.length === max) { result.push(current); return; }
if (open < n) { backtrack(current + "(", open + 1, close); }
if (close < open) { backtrack(current + ")", open, close + 1); } } backtrack("", 0, 0); return result;}
func generateParenthesis(n int) []string { max := n * 2 result := make([]string, 0) backtrack("", 0, 0, max, n, &result) return result}
func backtrack(current string, open int, close int, max int, n int, result *[]string) { if len(current) == max { *result = append(*result, current) return }
if open < n { backtrack(current+"(", open+1, close, max, n, result) }
if close < open { backtrack(current+")", open, close+1, max, n, result) }}
Pseudocode
Main function
- Create a variable
max
and set it ton * 2
- Create an empty array
result
- Create a function
backtrack
that takescurrent
,open
,close
as arguments - Call the
backtrack
function with an empty string""
,0
, and0
Backtracking function
- Check if the length of the current string is equal to
max
. If it is, add the current string to the result and return - If the number of open parentheses is less than
n
, call the backtrack function with the current string concatenated with an open parentheses(
,open + 1
, andclose
- If the number of close parentheses is less than the number of open parentheses, call the backtrack function with the current string concatenated with a close parentheses
)
,open
, andclose + 1
Complexity Analysis
- The time complexity of this algorithm is
O(4^n / sqrt(n))
as we are generating all possible combinations of parentheses. - The space complexity of this algorithm is
O(4^n / sqrt(n))
as we are using recursion to generate all possible combinations of parentheses.