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加上回溯条件,右括号数目不能超过左括号,还有就是左括号数最大不能超过n,代码如下:
class Solution {
public:
vector<string> generateParenthesis(int n) {
dfs(,n*,,,"");
return ret;
} void dfs(int dep, int maxDep, int left, int leftTotal, string curr){
if(leftTotal* > maxDep)
return;
if(dep == maxDep){
ret.push_back(curr);
return;
}
for(int i = ; i < ; i++){
if(i == ){
dfs(dep+, maxDep, left+, leftTotal+, curr+"(");
}else{
if(left)
dfs(dep+, maxDep, left-, leftTotal, curr+")");
}
}
}
private:
vector<string> ret;
};