当前位置:网站首页>LC301. 删除无效的括号
LC301. 删除无效的括号
2022-04-22 09:35:00 【weixin_44392348】
DFS+剪枝
def removeInvalidParentheses(self, s):
""" :type s: str :rtype: List[str] """
l = r = 0
for c in s:
if c == '(':
l += 1
elif c == ')':
if l:
l -= 1
else:
r += 1
ans = set()
def dfs(idx, cl, cr, dl, dr, path):
if idx == len(s):
if not dl and not dr:
ans.add(path)
return
if dl + dr > len(s) - idx: #后面的长度不够删了
return
if cr > cl or dl < 0 or dr < 0:
return
c = s[idx]
if c == '(':
dfs(idx+1,cl,cr,dl-1,dr, path)
elif c == ')':
dfs(idx+1,cl,cr,dl,dr-1, path)
dfs(idx+1,cl+(c=='('),cr+(c==')'),dl,dr,path+c)
dfs(0, 0, 0, l, r, "")
return list(ans)
DFS+去重剪枝
def removeInvalidParentheses(self, s):
""" :type s: str :rtype: List[str] """
l , r = 0,0
for c in s:
if c == '(':
l += 1
elif c == ')':
if l:
l -= 1
else:
r += 1
def helper(s):
sum = 0
for i in s:
if i == "(":
sum += 1
elif i == ")":
sum -= 1
if sum < 0:
return False
return sum == 0
res = []
def dfs(idx, dl, dr, s):
if dl == 0 and dr == 0:
if helper(s):
res.append(s)
return
for i in range(idx,len(s)):
if i > idx and s[i] == s[i-1]: #和组合总和一样,去除第一个后面的答案
continue
if dl+dr > len(s) - i:
break
if dl > 0 and s[i] == "(":
dfs(i, dl-1 ,dr, s[:i] + s[i + 1:])
if dr > 0 and s[i] == ")":
dfs(i,dl,dr-1,s[:i] + s[i + 1:])
dfs(0, l, r, s)
return res
版权声明
本文为[weixin_44392348]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_44392348/article/details/124329870
边栏推荐
猜你喜欢

Kernel pwn 基础教程之 Heap Overflow

遥感图像分割数据集整理(发布)

安装Navicat 15 详解及相关问题详解

IOS开发之——数据库-基础知识介绍(01)

QT 事件过滤器实例

idea中如何将Services调出并将启动类显示在Services中

ShardingSphere广播表和绑定表

Depth first search (I): middle order traversal of binary tree (force buckle)

【C语言进阶10——字符和字符串函数及其模拟实现(1)】

Understand the first snapshot read and the second snapshot read of the same transaction in MySQL mvcc - Notes
随机推荐
Heap overflow of kernel PWN basic tutorial
Write a simple examination program to complete the interaction of questions and answers on the console. Questions are divided into single choice and multi choice.
微搭低代码零基础入门课(第二课)
L2-030 Icelander (25 points) (nearest public ancestor)
Starting from the needs of popular science, doctor training and promotion of innovative medical equipment products, how does "baiyihua" layout medical visualization SaaS services?
云原生爱好者周刊:寻找 Netlify 开源替代品
在销量压力下,国产手机开始降价了,但还没有放下最后的面子
云数引领下,桑达股份2021年营收427.04亿元,同比增长33.21%
echo “新密码”|passwd --stdin 用户名
P型MOS管开关电路及工作原理详解-KIA MOS管
idea中如何将Services调出并将启动类显示在Services中
内存管理-
JS页面刷新方法汇总
etcd Watch 异常场景
杰理之AI Server【篇】
编写一个简单的考试程序,在控制台完成出题、答题的交互。试题(Question)分为单选(SingleChoice)和多选( MultiChoice)两种。
L2-033 简单计算器 (25 分)
网络抖动工具clumsy
Redis 内存回收策略
超越iTerm! 号称下一代终端神器,功能贼强大!