[英]Why does +1 works here but ++ operator doesn't
I am preparing for interviews and trying to practice recursion , here is my solution to a problem that ask to generate 'n' parenthesis ie if n=1 then[[()]] if n=2 then [[()()], [(())]] and so on..我正在准备面试并尝试练习递归,这是我对要求生成“n”括号的问题的解决方案,即如果 n=1 then[[()]] if n=2 then [[()()] , [(())]] 等等..
Here is my solution which works but if I increment the open before calling the recursive function it doesn't work, I have list both in the below code, not sure why this is happening :这是我的解决方案,但如果我在调用递归函数之前增加 open 它不起作用,我在下面的代码中列出了这两个,不知道为什么会发生这种情况:
public List<String> generateParenthesis(int n) {
List<String> rightAns = new ArrayList<>();
List<String> wrongAns = new ArrayList<>();
helper(0, 0, "", rightAns, n); //["((()))","(()())","(())()","()(())","()()()"] for n = 3
helperWrong(0, 0, "", wrongAns, n);//["((()))"] for n = 3
return rightAns;
}
public void helper(int open, int close, String cur, List<String> ans, int n){
if(cur.length() == 2*n){
ans.add(cur);
return;
}
if(open < n){
//open++; doesn't work
helper(open+1, close, cur+"(", ans, n);
}
if(close < open){
//close++; doesn't work
helper(open, close+1, cur+")", ans, n);
}
System.out.println("cur"+cur.toString());
return;
}
public void helperWrong(int open, int close, String cur, List<String> ans, int n){
if(cur.length() == 2*n){
ans.add(cur);
return;
}
if(open < n){
open++;
helperWrong(open, close, cur+"(", ans, n);
}
if(close < open){
close++;
helperWrong(open, close, cur+")", ans, n);
}
System.out.println("cur"+cur.toString());
return;
}
The postfix ++
operator is evaluated after the expresion.后缀++
运算符在表达式之后计算。 For example:例如:
a=2;
b=a++; //b=2, a=3
Same when calling functions:调用函数时相同:
a=2;
foo(a++);
//a=3
void foo(int v){
//v=2
}
So your recursive function will receive the value before it is incremented.因此,您的递归函数将在递增之前接收该值。
尝试++open
和++close
,并且 cdalxndr 已经解释了为什么它不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.