当前位置:网站首页>【LeetCode】22. 括号生成
【LeetCode】22. 括号生成
2022-06-25 03:53:00 【LawsonAbs】
1 题目
2 思想
使用深搜
每次有两种选择,入栈,出栈。然后判断得到的字符串结果是否合理即可。
n表示生产括号的对数
3 代码
import copy
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
self.dfs(n,n,res,[])
# print(res)
# tmp = []
# for i in res:
# if self.judge(i):
# tmp.append("".join(i))
return res
# 判断栈括号是否匹配
def judge(self,string):
left = 0
right = 0
for s in string:
if s == "(":
left += 1
else:
if left >0: # 说明有存货
left -=1
else:
return False
return True
# left 表示左括号个数,right表示右括号个数
def dfs(self,left,right,res,tmp):
if left == 0 and right ==0: # 全部放完了
if self.judge(tmp):
res.append(copy.deepcopy("".join(tmp)))
return
# 每次都有两种选择,放left还是放right?
if left:
tmp.append("(")
self.dfs(left-1,right,res,tmp)
tmp.pop()
if right:
tmp.append(")")
self.dfs(left,right-1,res,tmp)
tmp.pop()
边栏推荐
- Flutter FittedBox组件
- Does it count as staying up late to sleep at 2:00 and get up at 10:00? Unless you can do it every day
- Development of trading system (VII) -- Analysis of trading delay
- 【Harmony OS】【ArkUI】ets开发 图形与动画绘制
- 佐喃社区
- Redis related-01
- Lu Qi invests in quantum computing for the first time
- 《Missing Parts》NFT 作品集第 5 系列上线 The Sandbox 市场平台
- Create SQLite table with shell script and add SQL statement -- General
- Crawl Sina Weibo fans
猜你喜欢

DevEco Studio 3.0编辑器配置技巧篇

Flutter FittedBox组件

DAP data scheduling function improvement description

opencv怎么安装?opencv下载安装教程

How to quickly deliver high-value software

墨天轮访谈 | IvorySQL王志斌—IvorySQL,一个基于PostgreSQL的兼容Oracle的开源数据库

2. play the chromatic harmonica

AI writes its own code to let agents evolve! The big model of openai has the flavor of "human thought"

zabbix的安装避坑指南

【Harmony OS】【ArkUI】ets开发 图形与动画绘制
随机推荐
Lao Ye's blessing
Hello CTP (III) - CTP quotation API
Redis related-03
Jilin University 22 spring March "official document writing" assignment assessment-00084
windows 2003 64位系统php运行报错:1% 不是有效的 win32 应用程序
Create SQLite table with shell script and add SQL statement -- General
SEO的5大关键指标:排名+流量+会话+停留时长+跳出率
Crawl Sina Weibo fans
Simple integration of client go gin -update
Hello CTP (I) - basic knowledge of futures
Color NFT series representing diversity launched on the sandbox market platform
Flutter FittedBox组件
2.吹响半音阶口琴
Solution to the problem that Linux crontab timed operation Oracle does not execute (crontab environment variable problem)
【LeetCode】143. 重排链表
Standing wave ratio calculation method
Cesium 加载显示热力图
MySQL modifies and deletes tables in batches according to the table prefix
2. play the chromatic harmonica
What is the difference between learning code, rolling code and fixed code? The number of repeated codes, coding capacity and the principle of rolling code