i'm trying to understand a solution for the leetcode problem #22 where we generate parentheses recursively and I'm stuck on where the function returns to after we find the first combination of parentheses
the question asks you to create all possible valid (open and close correctly) combinations of n-parentheses pairs. so for n=2 the answer is a list being = [ "()()", "(())" ]
this is the code solution (credits: nick white):
class Solution {
// first
public List<String> generateParenthesis(int n) {
List<String> output_arr = new ArrayList();
backtrack(output_arr, "", 0, 0, n);
return output_arr;
}
// backtracking recursive method
public void backtrack (List<String> output_arr, String current_string, int open, int closed, int max){
// base case
if (current_string.length() == max*2){
output_arr.add(current_string);
return;
}
// recursive
if (open < max) backtrack(output_arr, current_string + "(", open+1, closed, max);
if (closed < open) backtrack(output_arr, current_string + ")", open, closed+1, max);
}
}
this is my interpretation of the recursive calls for an example case of n=2, but I'm not sure this is correct:
/*
example - n = 2
backtrack (output_arr, "", 0, 0, 2)
into method 2
if (cs.length == 4) add to output arr & return
if (open < 2) backtrack (output_arr, "(", 1, 0, 2 ); # A
if (closed < open) backtrack
into # A - backtrack (output_arr, "(", 1, 0, 2 );
if (cs.length == 4) add, return
if (open < 2) backtrack (output_arr, "((", 2, 0, 2 ); # B
if (closed < open) - do we come here after we fail to find anything in # H???
RETURNED HERE FROM # D - open = 1, closed = 0. closed < open
backtrack ( output_arr, "()", 1, 1, 2 ) # E
into # E
if (cs.length)
if (open <2) backtrack (output_arr, "()(", 2, 1, 2) # F
if (closed < open)
after into # G, we return HERE! lets call this #H closed is not less than open (1 == 1) now where do we go to?
into # F
if (cs.length)
if (open <2)
if (closed < open) backtrack (output_arr, "()()", 2, 2, 2) # G
int # G
if (cs.length)
output arr . add [ "(())", "()()" ]
return - WHERE TO ??
into # B
if (cs.length == 4) add, return
if (open <2)
if (closed < open) backtrack (out_arr, "(()", 2, 1, 2) # C
into # C
if ( cs.length == 4) add, return
if (open < 2)
if (closed < open) backtrack (out_arr, "(())", 2, 2, 2) # D
into # D
if ( cs.length == 4) add, return:
output arr ["(())"]
return -- WHERE DO WE RETURN TO?
*/