Simple BFS code Python


  • 0
    A
    class Solution(object):
        def generateParenthesis(self, n):
            queue = [("(",1,0)]
            result = []
            while queue:
                temp = []
                if len(queue[0][0]) == n*2:
                    break
                for elem in queue:
                    if elem[1] < n:
                        temp.append((elem[0]+"(",elem[1]+1,elem[2]))
                    if elem[2] < n and elem[2] < elem[1]:
                        temp.append((elem[0]+")",elem[1],elem[2]+1))
    
                queue = temp
            while queue:
                str = queue.pop()[0]
                result.append(str)
            return(result)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.