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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
给一个数字n,n代表几对括号,给出所有括号的排列。
思路:在string中插入“(”和“)”,每插入一个,计数值就减一。如何保证插入是正确的?
插入数量不超过n
可以插入 “)” 的前提是 “(” 的数量大于 “)”
下面这个图引用的是这个博客。(谢谢这位博主的手绘)
![](https://i-blog.csdnimg.cn/blog_migrate/1993ed0ed57a377eb40004ee047ec721.png)
问题可以转化为二叉树的形式,左分支添加左括号,右分支添加右括号。二叉树的数据结构形式是递归调用的,所以这道题可以用递归的方式求解。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
string s="";
addpar(res,s,n,n);
return res;
}
void addpar(vector<string>&v, string str, int left, int right){
if(left==0 && right==0){
v.push_back(str);
return;
}
if(left>0){
addpar(v,str+"(",left-1,right);
}
if(right>0 && left<right){
addpar(v,str+")",left,right-1);
}
}
};
自己对递归的方法还是以有些发怵,要加强理解多练习。