标签:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
AC代码:
class Solution(object): def generateParenthesis(self, n): if n < 1: return [‘‘] def backtracing(left, right, current, ret_list): if left > 0: backtracing(left - 1, right, current + ‘(‘, ret_list) if right > 0: if left == right: return backtracing(left, right - 1, current + ‘)‘, ret_list) else: ret_list.append(current) ret_list = [] backtracing(n, n, ‘‘, ret_list) return ret_list
用递归,找准递归出口即可。注意left==right的条件。
标签:
原文地址:http://www.cnblogs.com/zhuifengjingling/p/5229422.html