[LintCode] Generate Parentheses 生成括号

时间:2022-04-23 22:56:35

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

Have you met this question in a real interview?
Example

Given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

LeetCode上的原题,请参见我之前的博客Generate Parentheses

解法一:

class Solution {
public:
/**
* @param n n pairs
* @return All combinations of well-formed parentheses
*/
vector<string> generateParenthesis(int n) {
if (n == ) return {};
vector<string> res;
helper(n, n, "", res);
return res;
}
void helper(int left, int right, string out, vector<string>& res) {
if (left < || right < || left > right) return;
if (left == && right == ) {
res.push_back(out);
return;
}
helper(left - , right, out + "(", res);
helper(left, right - , out + ")", res);
}
};

解法二:

class Solution {
public:
/**
* @param n n pairs
* @return All combinations of well-formed parentheses
*/
vector<string> generateParenthesis(int n) {
set<string> res;
if (n == ) {
res.insert("");
} else {
vector<string> pre = generateParenthesis(n - );
for (auto a : pre) {
for (int i = ; i < a.size(); ++i) {
if (a[i] == '(') {
a.insert(a.begin() + i + , '(');
a.insert(a.begin() + i + , ')');
res.insert(a);
a.erase(a.begin() + i + , a.begin() + i + );
}
}
res.insert("()" + a);
}
}
return vector<string>(res.begin(), res.end());
}
};