22. Generate Parentheses

22. Generate Parentheses

Description

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

1
2
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

1
2
Input: n = 1
Output: ["()"]

Constraints:

  • 1 <= n <= 8

Hints/Notes

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
int n;
vector<string> res;
string path;

vector<string> generateParenthesis(int n) {
if (!n) {
return {};
}
this->n = n;
path = string(n * 2, 0);
dfs(0, 0);
return res;
}

void dfs(int left, int right) {
if (left == n && right == n) {
res.push_back(path);
return;
}
int index = left + right;
if (left < n) {
path[index] = '(';
dfs(left + 1, right);
}
if (right < left) {
path[index] = ')';
dfs(left, right + 1);
}
}
};