# Generate Parentheses Program Solution

We at gradjobopenings.com provide free job alerts of freshers job drives. In this website we list on campus job openings for freshers and off campus job openings for freshers and also work from home job openings. This is the best website to apply for off campus drive in India. Visit our website for government job alerts and private job alerts. We also list free interview notes and study materials, one of the best interview study website.comfortable to face the interviews:

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: ["()"]
```

Constraints:

• `1 <= n <= 8`

### Generate Parentheses Program Solution In C++

``````class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;

dfs(n, n, "", ans);
return ans;
}

private:
void dfs(int l, int r, string&& path, vector<string>& ans) {
if (l == 0 && r == 0) {
ans.push_back(path);
return;
}

if (l > 0) {
path.push_back('(');
dfs(l - 1, r, move(path), ans);
path.pop_back();
}
if (l < r) {
path.push_back(')');
dfs(l, r - 1, move(path), ans);
path.pop_back();
}
}
};
``````

### Generate Parentheses Program Solution In JAVA

``````class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<>();

dfs(n, n, new StringBuilder(), ans);
return ans;
}

private void dfs(int l, int r, final StringBuilder sb, List<String> ans) {
if (l == 0 && r == 0) {
return;
}

if (l > 0) {
sb.append("(");
dfs(l - 1, r, sb, ans);
sb.deleteCharAt(sb.length() - 1);
}
if (l < r) {
sb.append(")");
dfs(l, r - 1, sb, ans);
sb.deleteCharAt(sb.length() - 1);
}
}
}
``````

### Generate Parentheses Program Solution In PYTHON

``````class Solution:
def generateParenthesis(self, n):
ans = []

def dfs(l: int, r: int, s: str) -> None:
if l == 0 and r == 0:
ans.append(s)
if l > 0:
dfs(l - 1, r, s + '(')
if l < r:
dfs(l, r - 1, s + ')')

dfs(n, n, '')
return ans
``````
error: Content is protected !!