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

算法总结:括号类问题(Python),第1张

基本描述:

给定一个正整数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. 括号生成

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/571128.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存