If there's "(" quota, adding "(" is safe;
If there are more "(" than ")", which means quota["("]<quota[")"], adding ")" is safe.
class Solution {
public:
void helper(int l, int r, int n, string &sol, vector<string> &result) {
if(r==0 && l==0) {
result.push_back(sol);
return;
}
if(r<0 || l<0) return;
if(l>0) {
sol[n]='(';
helper(l-1,r,n+1,sol,result);
}
if(r>l) {
sol[n]=')';
helper(l,r-1,n+1,sol,result);
}
}
vector<string> generateParenthesis(int n) {
vector<string> result;
if(n==0) return result;
string sol(2*n,'(');//Note: string should be pre-allocated space
helper(n,n,0,sol,result);
return result;
}
};