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的更多相关文章

  1. [LeetCode] 301. Remove Invalid Parentheses 移除非法括号

    Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...

  2. LeetCode 301. Remove Invalid Parentheses

    原题链接在这里:https://leetcode.com/problems/remove-invalid-parentheses/ 题目: Remove the minimum number of i ...

  3. [leetcode]301. Remove Invalid Parentheses 去除无效括号

    Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...

  4. 【leetcode】301. Remove Invalid Parentheses

    题目如下: 解题思路:还是这点经验,对于需要输出整个结果集的题目,对性能要求都不会太高.括号问题的解法也很简单,从头开始遍历输入字符串并对左右括号进行计数,其中出现右括号数量大于左括号数量的情况,表示 ...

  5. 301. Remove Invalid Parentheses

    题目: Remove the minimum number of invalid parentheses in order to make the input string valid. Return ...

  6. 301. Remove Invalid Parentheses去除不符合匹配规则的括号

    [抄题]: Remove the minimum number of invalid parentheses in order to make the input string valid. Retu ...

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

  8. [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 ...

  9. [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 ...

随机推荐

  1. sea.js常用接口

    seajs.config 用来对 Sea.js 进行配置. seajs.config({ // 指定需要使用的插件 plugins: ['text', 'shim'], // 设置别名,方便调用 al ...

  2. JS - 常用效果代码库 (四)

    1.首字母大写示例: var value = “一段文本或一个参数”; value = value.toString() return value.charAt(0).toUpperCase() + ...

  3. jQuery属性操作(四)

    通过阅读jQuery为属性操作封装的基本方法和为处理兼容性问题提供的hooks,发现jQuery在属性操作方面并没有做过多的设计,只是处理一下兼容性问题,然后调用基础的DOM操作方法.以下是对JQue ...

  4. jquery validate使用笔记

    1 表单验证的准备工作 在开启长篇大论之前,首先将表单验证的效果展示给大家.     1.点击表单项,显示帮助提示 2.鼠标离开表单项时,开始校验元素  3.鼠标离开后的正确.错误提示及鼠标移入时的帮 ...

  5. HP P2xxx/MSA SMI-S Provider

    HP P2xxx/MSA SMI-S Provider The HP MSA provider must be enabled before it can be monitored. For more ...

  6. Redis+Keepalived实现高可用

    使用redis哨兵可以在主服务器出现故障的时候自动切换主从,但是从服务器的IP不同于原主服务器的IP还需要在客户端手动修改IP才能生效 下面使用keepalived实现VIP自动漂移 keepaliv ...

  7. Nginx防止恶意域名解析

    为了防止别人恶意将大量域名解析到自己的网站上面.我们可以对nginx做防止恶意域名解析,这样就只能通过自己的域名访问网站,其他域名就会显示错误500 打开Nginx配置文件nginx.conf,在原来 ...

  8. Ubuntu 16.04 ORB_SLAM2+ROS+usb_cam+AR

    Ubuntu 16.04 ORB_SLAM2+ROS+usb_cam+AR 参考博文:http://blog.csdn.net/u79501/article/details/68942174 http ...

  9. 1.4激活函数-带隐层的神经网络tf实战

    激活函数 激活函数----日常不能用线性方程所概括的东西 左图是线性方程,右图是非线性方程 当男生增加到一定程度的时候,喜欢女生的数量不可能无限制增加,更加趋于平稳 在线性基础上套了一个激活函数,使得 ...

  10. h5直播

    直播开发之旅 ① 状态控制: 目前我们先考虑直播的三种状态: 直播前,直播中,结束. 针对每个状态我们肯定会有不同的显示,这三种状态可以是三个页面,相互切换,或者一个页面,控制页面相关隐藏和显示. 可 ...