I have a very basic question about an algorithm to print all valid combinations of n-pairs of parentheses. I printed out the value of l, r and string s. But for the following code, after printing out the first combination which is (()), how the value of l and r become 1 and 0 so that it can start the second combination ()()?
static void brackets (int l, int r, String s) {
System.out.println(l + "" + r + " s:" + s);
if (l == 0 && r == 0) {
System.out.println(s);
}
if (l > 0) {
brackets(l-1, r+1, s + "(");
}
if (r > 0) {
brackets(l, r-1, s + ")");
}
}
public static void main(String[] args) {
brackets(2, 0, "");
}
l and r are left, right parentheses and I was expecting the output of: (()), ()() which are the two combinations of two pairs of parentheses. but how does this code get the second combination ()()? thanks