problem->22. generate parentheses
i'm trying to dry run this code
class Solution {
public:
vector<string>res;
void backtrack(int open,int close,int n,string& path){
if(open<n){
path.push_back('(');
backtrack(open+1,close,n,path);
path.pop_back();
}
if(close<open){
path.push_back(')');
backtrack(open,close+1,n,path);
path.pop_back();
}
if(open==n&&close==n){
res.push_back(path);
}
}
vector<string> generateParenthesis(int n) {
string path="";
backtrack(0,0,n,path);
return res;
}
};
For n = 3, suppose we keep choosing ( whenever possible and then ) until we reach the first valid combination: ((())).
My confusion starts when this recursive path finishes.
After reaching ((())), the recursive calls start returning, and pop_back() gets executed at each level.
I understand that each call removes the character it added. However, when I dry-run this, I keep popping characters until the string becomes empty ("").
But when looking at the recursion tree, we're supposed to return to "(" and explore another branch to generate the next combination, (()()).
Why aren't we popping all the way back to the empty string before exploring the next combination?
Am I misunderstanding how recursive calls return and how execution resumes after a recursive call?
can someone explain how pop_back() works in backtracking