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);
}
}
}
CodePudding user response:
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,
- If open is, say 2, after
open
, the value ofopen
is3
- However, when you do
open 1
, you only pass3
but the value ofopen
is still2
. 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.