Problem Statement:
Given an integer n, generate all combinations of well-formed parentheses with n pairs.
We can use a recursive function to explore different possibilities for forming valid parentheses. The function keeps track of the number of opening and closing brackets, as well as the temporary string formed during the process.
calculate):Parameters:
open_brackets: Number of opening brackets used so far.close_brackets: Number of closing brackets used so far.n: Total number of pairs required.s: A list to store valid parentheses combinations.t: Temporary string to build the current combination.Base Case:
open_brackets and close_brackets are both equal to n, append t to the list s and return.Recursive Steps:
open_brackets is less than n, add an opening bracket ( to t and recursively call the function with open_brackets + 1.close_brackets is less than open_brackets, add a closing bracket ) to t and recursively call the function with close_brackets + 1.generateParenthesis):result.calculate function with initial parameters:
open_brackets = 0, close_brackets = 0, n, result, and an empty string t.result containing all valid parentheses combinations.n = 3
((()))(()())(())()()(())()()()["((()))", "(()())", "(())()", "()(())", "()()()"]
Input:
n = 1
Output:
["()"]
Input:
n = 2
Output:
["(())", "()()"]
Input:
n = 3
Output:
["((()))", "(()())", "(())()", "()(())", "()()()"]
Input:
n = 0
Output:
[]
https://leetcode.com/problems/generate-parentheses/
Loading component...
Loading component...