class Solution { public List<String> generateParenthesis(int n) { List<String> ans = new ArrayList<String>(); StringBuilder temp = new StringBuilder(); dfs(0, n, ans, temp, 0, 0); return ans; } public void dfs(int i, int n, List<String> ans, StringBuilder temp, int leftcount, int rightcount){ if(temp.length() == 2*n){ ans.add(temp.toString()); return; } if(leftcount < n){ temp.append('('); dfs(i + 1, n, ans, temp, leftcount ++, rightcount); temp.deleteCharAt(temp.length() - 1); } if(rightcount < leftcount){ temp.append(')'); dfs(i + 1, n, ans, temp, leftcount, rightcount + 1); temp.deleteCharAt(temp.length() - 1); } } }这段代码有什么问题
时间: 2024-04-20 12:27:45 浏览: 16
这段代码存在一个问题:在递归调用时,使用了错误的自增运算符。具体来说,在调用 `dfs` 方法时,`leftcount` 参数应该传递 `leftcount + 1`,而不是 `leftcount++`。同样地,`rightcount` 参数应该传递 `rightcount + 1`,而不是 `rightcount++`。
修复后的代码如下:
```java
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<String>();
StringBuilder temp = new StringBuilder();
dfs(0, n, ans, temp, 0, 0);
return ans;
}
public void dfs(int i, int n, List<String> ans, StringBuilder temp, int leftcount, int rightcount){
if(temp.length() == 2*n){
ans.add(temp.toString());
return;
}
if(leftcount < n){
temp.append('(');
dfs(i + 1, n, ans, temp, leftcount + 1, rightcount);
temp.deleteCharAt(temp.length() - 1);
}
if(rightcount < leftcount){
temp.append(')');
dfs(i + 1, n, ans, temp, leftcount, rightcount + 1);
temp.deleteCharAt(temp.length() - 1);
}
}
}
```
修复后的代码会正确地生成有效的括号对,并将其添加到结果列表中。