Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
bfs takes n! time.. to get all the solutions.
class Solution(object):
def bfs(self, left, right, depth, n, string, result):
if depth == 2 * n:
result.append(string)
return
if left < n:
string += '('
self.bfs(left + 1, right, depth + 1, n, string, result)
string = string[:len(string) - 1]
if left > right:
string += ')'
self.bfs(left, right + 1, depth + 1, n, string, result)
string = string[:len(string) - 1]
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
self.bfs(0, 0, 0, n, '', result)
return result