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> res;
vector<string> generateParenthesis(int n) {
generate(n,n,"");
return res;
}
void generate(int left,int right,string s){
if(left == 0 && right == 0)
res.push_back(s);
else{
if(left > 0)
generate(left - 1,right,s + "(");
if(right > 0 && left < right)
generate(left,right - 1,s + ")");
}
}
};
参考
本文介绍了一个使用递归方法生成所有合法括号组合的C++算法。对于输入的整数n,该算法能生成所有可能的由n对括号组成的合法字符串集合。文中提供了一个具体的示例,展示了当n等于3时的全部解集,并附带了完整的源代码实现。
2056

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



