[英]Generate Parentheses in LeetCode
我正在解决问题在LeetCode上生成括号 。 我的第一个想法是可以从第n
对括号中推导出第n+1
对括号。 说,如果我们使用e
作为第n
个情况,而我认为第n+1
个情况将是以下情况之一:
(
+ e
+ )
()
+ e
e
+ ()
我想出了以下代码。
public class Solution {
public List<String> generateParenthesis(int n) {
HashSet<String> temp = new HashSet<String>();
HashSet<String> result = new HashSet<String>();
List<String> rsult = new ArrayList<String>();
if (n == 0) {
temp.add("");
return new ArrayList<String>(temp);
}
temp.add("()");
if (n == 1) {
return new ArrayList<String>(temp);
}
for (int i = 2; i <= n; i++) {
result.removeAll(temp);
for (String e : temp) {
if (!result.contains("(" + e + ")")) {
result.add("(" + e + ")");
}
if (!result.contains("()" + e)) {
result.add("()" + e);
}
if (!result.contains(e + "()")) {
result.add(e + "()");
}
}
temp.clear();
temp.addAll(result);
}
rsult = new ArrayList<String>(result);
Collections.sort(rsult);
return rsult;
}
}
但是,当我提交代码时,我发现我仍然错过了n+1
为偶数的情况。 所以我更新了我的代码如下。
public class Solution {
public List<String> generateParenthesis(int n) {
HashSet<String> temp = new HashSet<String>();
HashSet<String> result = new HashSet<String>();
List<String> rsult = new ArrayList<String>();
if (n == 0) {
temp.add("");
return new ArrayList<String>(temp);
}
temp.add("()");
if (n == 1) {
return new ArrayList<String>(temp);
}
for (int i = 2; i <= n; i++) {
result.removeAll(temp);
for (String e : temp) {
if (!result.contains("(" + e + ")")) {
result.add("(" + e + ")");
}
if (!result.contains("()" + e)) {
result.add("()" + e);
}
if (!result.contains(e + "()")) {
result.add(e + "()");
}
if (i % 2 == 0) {
String dblprt = new String();
for(int j = 0; j< i/2;j++) {
dblprt = "(" + dblprt + ")";
}
dblprt = dblprt + dblprt ;
if (!result.contains(dblprt)) {
result.add(dblprt);
}
}
}
temp.clear();
temp.addAll(result);
}
rsult = new ArrayList<String>(result);
Collections.sort(rsult);
return rsult;
}
}
尽管如此,测试用例还是失败了。 所以我很困惑。 为什么我的方式不起作用? 我还缺少一些案件吗?
为什么我的方式不起作用? 我还缺少一些案件吗?
考虑括号(())(())
,从算法中得出的唯一方法是,如果e = ())(()
,然后是(
+ e
+ )
但在这种情况下, e
不太适合形式的括号,因此e
永远不存在,并且您错过了一个案例。
编辑 :似乎您的第二个修订版解决了诸如()()
, (())(())
, ((()))((()))
但(()())(()())
还是(()())()(())
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.