22. Generate Parentheses
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
int left=n,right=n;
string temp;
if(n==0)
return res;
DFS(res,left,right,temp);
return res;
}
void DFS(vector<string> &res,int left,int right,string &temp){
if(left==0 && right==0){
res.push_back(temp);
return;
}
else{
if(left>0){
temp+='(';
left--;
DFS(res,left,right,temp);
temp.pop_back();
left++;
}
if(left<right && right>0){
temp+=')';
right--;
DFS(res,left,right,temp);
temp.pop_back();
right++;
}
}
}
};