void solve(int n,int open,int close,string s,vector<string>&ans) {
    if(open==close && close==n) {
        ans.push_back(s);
        return;
    }
    if(open<n) {
        s+="(";
        solve(n,open+1,close,s,ans);
        s.pop_back();
    }
    if(open>close) {
        s+=")";
        solve(n,open,close+1,s,ans);
        s.pop_back();
    }
}
vector<string> generateParentheses(int n) {
    vector<string> ans;
    solve(n,0,0,"",ans);
    return ans;
}
This piece of code generates all possible permutations of parantheses for a given value n. I can easily dry run the code when n=2 and reach to the output "(())". But I really don't understand how it reaches to "()()".
The point where I get stuck is "()". The code can't close the bracket till the no of opening brackets is equal to n.
 
    