题目描述
思路分析
dfs暴搜
dfs参数是搜索的位置,根据该位置左右括号的数量。分别从“该位置放左括号“和“该位置放右括号”来扩展。
剪枝:任意一种括号大于n个或者某个位置左括号数量大于右括号数量,则直接
r
e
t
u
r
n
return
return
代码实现
class Solution {
public:
void dfs(int cur,int cntl,int cntr,string curs,int n,vector<string>& ans){
if(cntl>n||cntr>n) return;
if(cntl<cntr) return;
if(cur==2*n+1){
ans.push_back(curs);
return;
}
if(cntl==cntr){
curs.push_back('(');
dfs(cur+1,cntl+1,cntr,curs,n,ans);
}
else if(cntl>cntr){
curs.push_back('(');
dfs(cur+1,cntl+1,cntr,curs,n,ans);
curs.pop_back();
curs.push_back(')');
dfs(cur+1,cntl,cntr+1,curs,n,ans);
}
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
string curs;
dfs(1,0,0,curs,n,ans);
return ans;
}
};