(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个。''
表示当前以组成的字符串
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现