|
用networkx实现方法:
- import networkx as nx
- def balanced_parens(n):
- G = nx.DiGraph()
- G.add_node((0, 0), label='(')
-
- for i in range(1, 2*n+1):
- for node in list(G.nodes):
- count_open, count_close = node
- if count_open < n: # 左边个数小于n增加一条边标签是(
- G.add_edge(node, (count_open+1, count_close), label='(')
- if count_open > count_close: # 右边小于左边,增加一条边,)
- G.add_edge(node, (count_open, count_close+1), label=')')
-
- paths = []
- for path in nx.all_simple_paths(G, (0, 0), (n, n)): # 最开始点到终点的最短路径
- paths.append(''.join([G.edges[edge]['label'] for edge in zip(path[:-1], path[1:])]))
- return paths
复制代码 |
-
00点到33点路径标签就是结果
|