【发布时间】:2013-12-12 06:30:16
【问题描述】:
def paren(n):
lst = ['(' for x in range(n)]
current_string = ''.join(lst)
solutions = list()
for i in range(len(current_string)+1):
close(current_string, n, i, solutions)
return solutions
def close(current_string, num_close_parens, index, solutions):
"""close parentheses recursively"""
if num_close_parens == 0:
if current_string not in solutions:
solutions.append(current_string)
return
new_str = current_string[:index] + ')' + current_string[index:]
if num_close_parens and is_valid(new_str[:index+1]):
return close(new_str, num_close_parens-1, index+1, solutions)
else:
return close(current_string, num_close_parens, index+1, solutions)
def is_valid(part):
"""True if number of open parens >= number of close parens in given part"""
count_open = 0
count_close = 0
for paren in part:
if paren == '(':
count_open += 1
else:
count_close += 1
if count_open >= count_close:
return True
else:
return False
print paren(3)
上面的代码是我解决上述问题的尝试。它为n<3 提供了足够的解决方案,但除此之外,它并没有给出所有的解决方案。例如,当n=3 时,它输出['()()()', '(())()', '((()))'],而省略'()(())'。如何修改代码以正确输出所有可能的解决方案?
【问题讨论】:
-
而且还得这样递归解决?
-
这似乎你想使用深度/广度优先搜索和回溯。画出 n=3 的有效解,它形成一个明显的图形。 behold, the mspaint
-
@Smac89 不,其中大多数无效。
-
你说得对,我刚刚意识到 OP 想要“有效”而不是所有组合
-
@roippi 请参阅 en.wikipedia.org/wiki/Catalan_number 中的插图 :)
标签: python recursion backtracking