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:void helper(vector<string> & solution, string & singleSolution,
int numofleft, int numofright, int n){
if (singleSolution.size()==2*n)
solution.push_back(singleSolution);
else{
if (numofleft<n){
singleSolution += '(';
helper(solution, singleSolution, numofleft+1, numofright, n);
singleSolution = singleSolution.substr(0, singleSolution.size()-1);
}
if (numofright<numofleft){
singleSolution += ')';
helper(solution, singleSolution, numofleft, numofright+1, n);
singleSolution = singleSolution.substr(0, singleSolution.size()-1);
}
}
}
vector<string> generateParenthesis(int n) {
vector<string> solution;
string singleSolution = "";
helper(solution, singleSolution, 0, 0, n);
return solution;
}
};
本文介绍了一个使用递归方法生成所有有效括号组合的C++实现。对于给定的n对括号,通过控制左括号和右括号的数量来确保生成的字符串总是有效的。文章详细展示了如何使用递归辅助函数来构建所有可能的有效括号组合。
2046

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



