题目: 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:
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
题意: 给出一个数值n,要求列举出所有括号匹对的情况
分析: 因为括号匹对的关系,左括号数要等于右括号数,且对于任意一点,改点之前的左括号数永远大于或者等于右括号数,因此,此题可以用递归的方法求解,能先加"(“就先加”(",不能加了就加“)”。
代码如下:
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
def generate(right, left, p,parent=[]):
if left:
parent = generate(right, left-1, p+"(", parent)
if right > left:
parent = generate(right-1, left, p+")", parent)
if right == 0:
parent.append(p)
return parent
return generate(n, n, "")