题目
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
class Solution {
public:
vector<string> res;
void dfs(string &str,int n,string s){
int left_num=count(str.begin(),str.end(),'(');
int right_num=count(str.begin(),str.end(),')');
if(left_num>n||left_num<right_num){//画出递归树,发现回溯条件
return;
}
else if(str.length()==n*2){//递归终止
res.push_back(str);
}
else{
for(int i=0;i<s.length();i++){
str=str+s[i];
dfs(str,n,s);
str.pop_back();
}
}
}
vector<string> generateParenthesis(int n) {
string str;
string s="()";
dfs(str,n,s);
return res;
}
};