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;
if(n<=0) return res;
//string tmp;
dfs(res,"",n,n);
return res;
}
void dfs(vector<string> &res,string tmp,int left,int right)
{
if(left==0&&right==0)
{
res.push_back(tmp);
return;
}
if(left>0) dfs(res,tmp+'(',left-1,right);
if(left<right) dfs(res,tmp+')',left,right-1);
}
};
本文介绍了一个使用深度优先搜索(DFS)算法生成所有有效括号组合的方法。针对输入的整数n,该算法能够生成所有可能的有效括号字符串组合。通过递归地添加左括号和右括号,并确保任何时候右括号的数量不超过左括号的数量来实现。
2042

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



