Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
char *str = new char[(2*n)+1];
str[2*n] = '\0';
generate(res, str, 0, 0, 2*n);
return res;
}
void generate(vector<string>& res, char *str, int left, int cur, int n) {
if (left == 0 && cur == n) {
res.push_back(str);
return ;
}
if (left == 0) {
str[cur] = '(';
generate(res, str, 1, cur+1,n);
} else {
if (left + cur < n) {
str[cur] = '(';
generate(res, str, left+1, cur+1, n);
}
str[cur] = ')';
generate(res, str, left-1, cur+1,n);
}
}
};

本文介绍了一个使用递归方法生成所有合法括号组合的C++实现。对于给定的正整数n,该算法能生成所有可能的且由n对括号组成的合法字符串。通过递归构造左右括号来确保每种组合都是有效的。
746

被折叠的 条评论
为什么被折叠?



