[LeetCode] 301. Remove Invalid Parentheses_Hard tag:BFS
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 ).
Example 1:
Input: "()())()"
Output: ["()()()", "(())()"]
Example 2:
Input: "(a)())()"
Output: ["(a)()()", "(a())()"]
Example 3:
Input: ")("
Output: [""]
这个题目的思路参考地址,是用Java写的, 不得不说, 太牛逼了.
主要思路我理解为, 利用Count去看一个valid parentheses, 然后一旦发现不是valid的时候, 那么我们就在目前的部分string里面, 分别将 ')' 去掉一个, 但是这样会出现的问题是我们可能有重复的情况, 比如说s = ()), we can remove s[1] or s[2] but the result is the same (). Thus, we restrict ourself to remove the first ) in a series of concecutive )s.
那么去掉多余的')' 之后, prefix 变成valid, 然后再recursively call 剩下的string, 但是我们只需要再从上次remove掉的那个位置开始检测即可,否则的话又有重复的. For this, we keep tracking the last removal position and only remove ‘)’ after that.
以上的做法就是去掉多余的')', 比如"()()())", 但是没有办法解决"()()("这样的情况, 那么思路类似,就是将以上的做法, 从右向左走一遍, 然后count计数的时候调换下顺序即可, 但是这个思路牛逼的地方就是,它将s reverse, 然后还是用原来的code, 只是加多一个parameter pairs即可. 实在是太牛逼了. 如果还是看不懂的话建议去看上面参考地址的解释, 很详细, 都是英文, 但是解释的肯定比我好, 比我清楚. 不得不再说一次, 真的太腻害了!
Update from 04/10/2020:
必须有prej,不能只有prei,否则的话input为“()()(())))()”, 因为会错过在有‘)’之前的多余的选择。
有prej:
['(((())))()', '(()(()))()', '()((()))()', '()()(())()']
无prej:
['(()(()))()', '()((()))()', '()()(())()']
1. Constraints
1) s可以为empty
2) 每个元素可以是除了"()"之外的元素
2. Idea
利用所谓的recursive helper function 去帮忙, 不知道时间复杂度是多少.
3.Code:
class Solution:
def removeInvalidParentheses(self, s):
def helper(s, ans, prei, prej, pairs):
count = 0
for i in range(prei, len(s)):
if s[i] == pairs[0]: count += 1
if s[i] == pairs[1]: count -= 1
if count >= 0: continue
for j in range(prej, i+1): # note it is i+1, because until i
if s[j] == pairs[1] and (j == prej or s[j-1] != s[j]):
helper(s[:j] + s[j+1:], ans, i, j, pairs) # should be i + 1, and j + 1, but delete s[j], so i + 1 - 1, j + 1 - 1, in the end i and j
return # the reason it has a return here is finish the helper if it gets into the loop j, otherwise will keep looping for i even the counter is -1.
revs = s[::-1]
if pairs[0] == '(':
helper(revs, ans, 0, 0, ")(")
else:
ans.append(revs)
18 ans = []
19 helper(s, ans, 0, 0, "()")
20 return ans
4. Test cases
1) ""
2) "()"
3) "())"
4) "(()"
5)
"()())()"
[LeetCode] 301. Remove Invalid Parentheses_Hard tag:BFS的更多相关文章
- [LeetCode] 301. Remove Invalid Parentheses 移除非法括号
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...
- LeetCode 301. Remove Invalid Parentheses
原题链接在这里:https://leetcode.com/problems/remove-invalid-parentheses/ 题目: Remove the minimum number of i ...
- [leetcode]301. Remove Invalid Parentheses 去除无效括号
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...
- 【leetcode】301. Remove Invalid Parentheses
题目如下: 解题思路:还是这点经验,对于需要输出整个结果集的题目,对性能要求都不会太高.括号问题的解法也很简单,从头开始遍历输入字符串并对左右括号进行计数,其中出现右括号数量大于左括号数量的情况,表示 ...
- 301. Remove Invalid Parentheses
题目: Remove the minimum number of invalid parentheses in order to make the input string valid. Return ...
- 301. Remove Invalid Parentheses去除不符合匹配规则的括号
[抄题]: Remove the minimum number of invalid parentheses in order to make the input string valid. Retu ...
- [LeetCode] 310. Minimum Height Trees_Medium tag: BFS
For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ...
- [LeetCode] 127. Word Ladder _Medium tag: BFS
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- [LeetCode] 101. Symmetric Tree_ Easy tag: BFS
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...
随机推荐
- 【Nginx】服务器中HTTP 301跳转到带www的域名的方法
从nginx的官方文档 documentation, 正确的nginx https 301跳转到带www域名方法的方法如下: HTTP 301跳转到带www域名方法 需要两个server段. serv ...
- ubuntu apt 代理设置
可以通过三种方法为apt-get设置http代理方法一这是一种临时的手段,如果您仅仅是暂时需要通过http代理使用apt-get,您可以使用这种方式.在使用apt-get之前,在终端中输入以下命令(根 ...
- Qt编写activex控件在网页中运行
qt能够实现的东西非常多,还可以写activex控件直接在网页中运行.参照qtdemo下的例子即可. 方案一:可执行文件下载:https://pan.baidu.com/s/14ge9ix2Ny0x7 ...
- 使用Struts时,JSP中如何取得各个会话中的参数值?
· request <s:property value="#request.req"/> 或者 ${requestScope.req} · session <s: ...
- jQuery().end()的内部实现及源码分析
jQuery().end()的作用是返回当前jQuery对象的上一个状态. 1.end()源码: // 所有通过pushStack方法获得的jQuery对象都可以通过end方法返回之前的状态 // ...
- SSH用户枚举漏洞(CVE-2018-15473)原理学习
一.漏洞简介 1.漏洞编号和类型 CVE-2018-15473 SSH 用户名(USERNAME)暴力枚举漏洞 2.漏洞影响范围 OpenSSH 7.7及其以前版本 3.漏洞利用方式 由于SSH本身的 ...
- 一篇博客搞定redis基础
redis简介 redis 一款高性能key-value数据库,实际上多用作缓存队列或者消息分发(celery),但是最常常被用来做缓存. redis安装 源码安装 $ wget http://dow ...
- 网卡bonding模式 - bond0、1、4配置
网卡bonding模式 - bond0.1.4配置 网卡bonding简介 网卡绑定就是把多张物理网卡通过软件虚拟成一个虚拟的网卡,配置完毕后,所有的物理网卡的ip和mac将会变成相同的.多网卡同时工 ...
- oracle dblink 查询 tns:无法解析指定的连接标识符
问题情景是这样的:我在数据库服务器(windows server 2008r2 ,64bit)oracle(11gr2,64bit)中通过dblink连接到另外一台服务器(hp-ux)的oracle( ...
- iOS的socket开发基础
目录[-] socket简介 tcp和udp的区别 TCP三次握手和四次挥手 TCP三次握手 tcp四次挥手 tcpsocket和udpsocket的具体实现 tcpsocket的具体实现 udpso ...