[Geeks for Geeks] Generate Parentheses

Generate Parentheses

Given an integer N representing the number of pairs of parentheses, the task is to generate all combinations of well-formed(balanced) parentheses.

  • Time : O(2^n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
vector<string> res;
void helper(string& build, int open, int close, int n) {
if(build.length() == n) res.push_back(build);
else {
if(open) {
build.push_back('(');
helper(build, open - 1, close, n);
build.pop_back();
}
if(close > open) {
build.push_back(')');
helper(build, open, close - 1, n);
build.pop_back();
}
}
}
public:
vector<string> AllParenthesis(int n) {
res.clear();
helper(string() = "", n, n, 2 * n);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/26/PS/GeeksforGeeks/generate-all-possible-parentheses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.