LeetCode-Q22-Generate Paretheses

来源:互联网 发布:朗读英语的软件 编辑:程序博客网 时间:2024/06/08 07:50

DFS:先遍历左括号,再补齐右括号

def generateParenthsis(n):    def dfs(res, s, l, r):        if l==0 and r==0:            res.append(s)        if(l>0):            dfs(res, s+'(', l-1, r)        if(r>l):            dfs(res, s+')', l, r-1)    res = []    dfs(res, '', n, n)    return res


BFS:对每一个左括号,先补齐右括号

def generateParenthsis(n):    def bfs(res, s, l, r):        if l==0 and r==0:            res.append(s)        if(r>l):            bfs(res, s+')', l, r-1)        if(l>0):            bfs(res, s+'(', l-1, r)    res = []    bfs(res, '', n, n)    return res

可见,BFS与DFS在实现上几乎一样,关键在于处理的顺序。
关于BFS与DFS更加简洁的实现区别可见stackoverflow问题Non recursive Depth first search algorithm