一、Problem
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Input: "()())()"
Output: ["()()()", "(())()"]
Example 2:
Input: "(a)())()"
Output: ["(a)()()", "(a())()"]
Example 3:
Input: ")("
Output: [""]
二、Solution
方法一:bfs
只要是搜索都是枚舉所有情況,然後篩選合法情況,最後得出解,bfs 也不例外,這題要求的是刪除最少的括號,所以可以用 bfs 做一下
- 檢查刪除字符串的每一個字符 next 得到的所有字符串是否合法。
- 只要 next 合法,就找到了一種刪除最少的方案,那麼該方案下的所有其它刪法都不是 “最少” 的,所以可以退出 bfs 了。
- 最後只需要將 queue 中合法的字符串添加進 ans 即可。
class Solution {
boolean valid(String s) {
int left = 0;
for (char c : s.toCharArray()) {
if (c == '(')
left++;
else if (c == ')' && --left < 0)
return false;
}
return left == 0;
}
public List<String> removeInvalidParentheses(String s) {
List<String> ans = new LinkedList<>();
Queue<String> q = new LinkedList<>();
q.add(s);
Set<String> vis = new HashSet<>();
boolean found = false;
while (!q.isEmpty()) {
String cur = q.poll();
if (valid(cur)) {
ans.add(cur);
break;
}
for (int i = 0; i < cur.length(); i++) {
if (Character.isLetter(cur.charAt(i)))
continue;
String next = cur.substring(0, i) + cur.substring(i+1);
if (!vis.contains(next)) {
vis.add(next);
q.add(next);
}
}
}
for (String ss : q) if (valid(ss))
ans.add(ss);
return ans;
}
}
複雜度分析
- 時間複雜度:,n 爲
- 空間複雜度:,
方法二:dfs
代辦,
複雜度分析
- 時間複雜度:,
- 空間複雜度:,