# Generate Parentheses LeetCode Solution

Here, We see Generate Parentheses LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

# List of all LeetCode Solution

## Problem Statement

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: [“()”]

## Generate Parentheses Leetcode SolutionC++

``````class Solution {
public:
vector<string> generateParenthesis(int n) {
int open = n;
int close = n;
vector<string> ans;
string op = "";
solve(op, open, close, ans);
return ans;
}
void solve(string op, int open, int close, vector<string> &ans){
if(open == 0 && close == 0){
ans.push_back(op);
return;
}
if(open == close){
string op1 = op;
op1.push_back('(');
solve(op1, open-1, close, ans);
}
else if(open == 0){
string op1 = op;
op1.push_back(')');
solve(op1, open, close-1, ans);
}
else if(close == 0){
string op1 = op;
op1.push_back('(');
solve(op1, open-1, close, ans);
}
else{
string op1 = op;
string op2 = op;
op1.push_back('(');
op2.push_back(')');
solve(op1, open-1, close, ans);
solve(op2, open, close-1, ans);
}
}
};```Code language: JavaScript (javascript)```

## Generate Parentheses Leetcode SolutionJava

``````class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
recurse(res, 0, 0, "", n);
return res;
}
public void recurse(List<String> res, int left, int right, String s, int n) {
if (s.length() == n * 2) {
return;
}
if (left < n) {
recurse(res, left + 1, right, s + "(", n);
}
if (right < left) {
recurse(res, left, right + 1, s + ")", n);
}
}
}```Code language: JavaScript (javascript)```

## Generate Parentheses SolutionJavaScript

``````var generateParenthesis = function(n) {
const output = [];
const dfs = (str, open, close) => {
if (open > close) {
return;
}
if (open === 0 && close === 0) {
output.push(str);
return;
}
if (open > 0) {
dfs(`\${str}(`, open - 1, close);
}
if (close > 0) {
dfs(`\${str})`, open, close - 1);
}
};
dfs('', n, n);
return output;
};```Code language: JavaScript (javascript)```

## Generate Parentheses SolutionPython

``````class Solution(object):
def generateParenthesis(self, n):
def dfs(left, right, s):
if len(s) == n * 2:
res.append(s)
return
if left < n:
dfs(left + 1, right, s + '(')
if right < left:
dfs(left, right + 1, s + ')')
res = []
dfs(0, 0, '')
return res``````
Scroll to Top