I was working on Leetcode #22 Generate Parentheses. In one of their solutions, I noticed if we change open+1
and close+1
to ++open
and ++close
, the code doesn't work anymore. I thought we could still use pre-increment in recursion, so I don't understand what makes the difference here.
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList();
backtrack(ans, new StringBuilder(), 0, 0, n);
return ans;
}
public void backtrack(List<String> ans, StringBuilder cur, int open, int close, int max){
if (cur.length() == max * 2) {
ans.add(cur.toString());
return;
}
if (open < max) {
cur.append("(");
backtrack(ans, cur, open+1, close, max);
cur.deleteCharAt(cur.length() - 1);
}
if (close < open) {
cur.append(")");
backtrack(ans, cur, open, close+1, max);
cur.deleteCharAt(cur.length() - 1);
}
}
}
The difference between passing value using ++open
and open+1
is that in the former, the value of the variable open
is changed, while in the latter it is not. That is,
++open
, the value of open
is 3
open+1
, you only pass 3
but the value of open
is still 2
. So, the next loop gets the same value.To better understand, the following is equivalent to ++open
:
backtrack(ans, cur, (open = open+1), close, max);
In the above code, the bracketed expression is evaluated to set the value of open
to open+1
before being passed to the method.