我正在努力解决问题Generate Parentheses on LeetCode。我的第一个想法是n+1
对括号可以从n
对括号中推断出来。说,如果我们使用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;
}
}
然而,测试用例失败了。所以我很困惑。为什么我的方式不起作用?我还记得一些情况吗?
答案 0 :(得分:0)
为什么我的方式不起作用?我还记得一些情况吗?
考虑括号Scroll rect
,来自您的算法的唯一方法是(())(())
,然后是e = ())(()
+ (
+ e
但是在这种情况下,)
不是一个格式正确的括号,因此e
从未存在过,你错过了一个案例。
编辑:您的第二次修订似乎解决了e
,()()
,(())(())
等案例但((()))((()))
或(()())(()())
?