i'm a little bit confused about the stack status for a well-known problem , Valid Permutation of Parenthesis
there are many articles and solutions in the Internet for this and one of simple solutions is
static void allParen1( int l, int r, int n, String str ) {
if( r == n ) {
System.out.println(str + " <" + l + ": " + r + ">");
return;
}
if( l < n ) {
allParen1( l + 1, r, n, str +"(" );
}
if( r < l ) {
allParen1( l, r + 1, n, str + ")");
}
}
and if I draw a recursion tree for this code is
but I don't clearly understand that how each subtree is initiated properly.
For example, after going down the left most subtree in the figure,
it's going up to ((
and then start the second left most subtree (()
, ...
I draw a part of stack status of the recursion tree below.
1. My first question is how stack pops only down to
(((
in the first stack (1)
which corresponds to going up the tree and then start the second left most subtree in stack (2)
in the code?
Why the stack doesn't pop down to something else like ((()
or ((())
or (
in the first stack (1) in the given code?
Maybe I don't still clearly understand how recursion and backtracking works.
2.They say this problem is using backtracking. backtracking is happening if a certain condition doesn't meet before going further down to a recustion tree, it doesn't go gown and just branching out to a different subtree like N-Queen problem.
Even though this problem doesn't have such condition to stop going down to a recursion tree. how this is called backtracking problem?