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...
void calculate(int openN , int closeN, int n , vector<string>& s, string t){
if(openN == n && closeN == n) {
s.push_back(t);
return;
}
if(openN < n) {
t.push_back( '(' );
calculate(openN+1 , closeN, n , s, t);
t.pop_back();
}
if(closeN < openN){
t.push_back( ')' );
calculate(openN , closeN+1 , n , s , t);
t.pop_back();
}
return ;
}//function end
Input: n = 1
Output: ["()"]
vector<string> generateParenthesis( int n ) {
string t = "";
vector<string>s;
calculate(0,0,n,s,t);
return s;
}//function end
Utility Function is not required.