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對括號的所有有效組合?
怎麼樣'(()() )'? – RedBaron
它必須以這種方式遞歸解決嗎? –
這看起來像你想要使用深度/廣度優先搜索和回溯。勾畫出n = 3的有效解,並形成一個明顯的圖。 [注意,mspaint](http://i63.photobucket.com/albums/h139/roippi/DFSparen_zpsf0262e2d.png) – roippi