22 Generate Parentheses
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]vector<int> find_left_paren_loc(const string &s) {
vector<int> locs;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(')
locs.push_back(i);
}
return locs;
}
vector<string> _generateParenthesis(int n, vector<string> &prev, unordered_set<string> &unique) {
if (n > 0) {
vector<string> next;
for (string &s : prev) {
vector<string> candidates;
vector<int> left_locs = find_left_paren_loc(s);
for (int i : left_locs) {
string str_cp = s;
candidates.push_back(str_cp.insert(i + 1, "()"));
}
candidates.push_back("()" + s);
for (const string &s1 : candidates) {
if (unique.find(s1) == unique.end()) {
next.push_back(s1);
unique.insert(s1);
}
}
}
return _generateParenthesis(n - 1, next, unique);
}
return prev;
}
vector<string> generateParenthesis(int n) {
unordered_set<string> unique;
vector<string> prev;
prev.push_back("");
return _generateParenthesis(n, prev, unique);
}
int main()
{
for (int i : {0, 1, 2, 3, 4, 5, 6}) {
print(generateParenthesis(i));
cout << endl;
}
}Last updated

