算法总结:括号类问题(Python)

基本描述:

给定一个正整数n,请写出可以生成的有效括号数量(给出所有括号的组合)

基本思路:

深度优先搜索(DFS),回溯

深搜模板:    

1. 参数以及终止条件:

        参数就是n,以及已经使用的左括号数量left ,右括号数量right

        终止条件 path数组中的元素数量 = 2 * n

if len(path) == 2 * n:
    res.append(''.join(path[:]))
    return 

2.单层逻辑:

(1) path数组中的 ' ( ' 数量 >= ' ) '数量, 即left >= right

if left > right:
    path.append(')')
    dfs(path, left, right + 1)
    path.pop()

          (2)    ' ( '数量left < = n

if left < n:
    path.append('(')
    dfs(path, left + 1, right)
    path.pop()

整体代码:

ans = []
def dfs(path, left, right):
    if len(path) == 2 * n:
        ans.append("".join(path[:]))
        return 
    if left < n:
        path.append("(")
        dfs(path, left + 1, right)
        path.pop()
    if right < left:
        path.append(")")
        dfs(path, left, right + 1)
        path.pop()   # 回溯
dfs([], 0, 0)
return ans

若是数量问题就把终止条件那里的

ans.append(''.join(path[:]))

改为 ans  += 1

类型题链接:

22. 括号生成

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值