Generate Parentheses Problem
Description
LeetCode Problem 22.
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
Sample C++ Code
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
33
34
class Solution {
public:
string paren = "()";
vector<string> ans;
int N;
void dfs(string& s, int left, int right) {
if (s.size() == N*2) {
ans.push_back(s);
return;
}
if (left < N) {
s += '(';
dfs(s, left+1, right);
s.pop_back();
}
if (right < left) {
s += ')';
dfs(s, left, right+1);
s.pop_back();
}
}
vector<string> generateParenthesis(int n) {
N = n;
string s;
dfs(s, 0, 0);
return ans;
}
};