java - 为什么 +1 在这里有效,但 ++ 运算符不在这里
问题描述
我正在准备面试并尝试练习递归,这是我对一个要求生成“n”括号的问题的解决方案,即如果 n=1 then[[()]] if n=2 then [[()()] , [(())]] 等等..
这是我的解决方案,但如果我在调用递归函数之前增加 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;
}
解决方案
后缀++
运算符在表达式之后进行评估。例如:
a=2;
b=a++; //b=2, a=3
调用函数时相同:
a=2;
foo(a++);
//a=3
void foo(int v){
//v=2
}
因此,您的递归函数将在递增之前接收该值。
推荐阅读
- git - 在 W10 上使用 Yubikey 在 PowerShell 中通过 SSH 进行 git 克隆
- node.js - 在 node.js 中运行同步代码而不阻塞的正确方法
- python - scipy fft 返回空虚部
- angular - 运行 ng e2e 时出现此错误:找不到 update-config.json
- reactjs - 将子组件保存在数组中并使用它的道具搜索组件是否可以?
- c# - dataGridView 中的 Alpha 背景替换为白色背景(第一次数据填充)
- java - 在 JPA 实体上应用 Jackson 的 Stakover 流错误以生成 JSON
- python - 如何在 Python 中使用 selenium 提取“查看更多”中的文本?
- java - 动态更新哈希图中值的特定部分
- php - Laravel Nova 无法在实时服务器上呈现登录页面