(python)代码学习||2024.2.4||题目是codewars的【 All Balanced Parentheses】

题目链接:https://www.codewars.com/kata/5426d7a2c2c7784365000783/python

def balanced_parens(n):
'''
To construct all the possible strings with n pairs of balanced parentheses
this function makes use of a stack of items with the following structure:
(current, left, right)
Where:
current is the string being constructed
left is the count of '(' remaining
right is the count of ')' remaining
'''
stack = [('', n, 0)]
result = []
# Loop until we run out of items in the stack
while stack:
current, left, right = stack.pop()
# if no '(' or ')' left to add, add current to the result
if left == 0 and right == 0:
result.append(current)
# if we can, add a '(' and return to the stack
if left > 0:
stack.append((current + '(', left - 1, right + 1))
# if we can, add a ')' and return to the stack
if right > 0:
stack.append((current + ')', left, right - 1))
return result

只有在放置了'('后才能放置')',因此stack中初始的元素('',n,0)中,n表示可放置的(有n个,0表示可放置的')'有0个。''表示当前以组成的字符串

posted @   Kazuma_124  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示