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:
"((()))", "(()())", "(())()", "()(())", "()()()"
这个题的难点在于dfs的关系不是那么的明确。。。害我试了好久,不过话说回来还是自己菜。
就是每次dfs一层,都去加一个“(”,然后再去考虑 加右括号,分别加0-m个,其中m表示有效的右括号个数,即右括号个数不能比左括号个数多。
class Solution {
public:
vector<string> v;
vector<string> generateParenthesis(int n) {
dfs("",0,n);
return v;
}
void dfs(string path,int left,int n){
path+="(";
left++;
if(left==n){
for(int i=path.length();i<2*n;i++)
path+=")";
v.push_back(path);
return;
}
//right parenthese
string tmp = "";
for(int i=0;i<=(left-((int)path.length()-left));i++){
dfs(path+tmp,left,n);
tmp+=")";
}
}
};