[英]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.