利用括号序列规律,递归回溯生成。
class Solution {
public:
vector<string> res;
string path;
vector<string> generateParenthesis(int n) {
dfs(0,0,n);
return res;
}
void dfs(int left, int right, int n){
if(left==n&&right==n){
res.push_back(path);
return;
}
if(left<=n){
path+='(';
dfs(left+1,right,n);
path.pop_back();
}
if(right<=n&&right<left){
path+=')';
dfs(left,right+1,n);
path.pop_back();
}
}
};