题目
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=N, 每一个可行的解都可以由一对”(“、”)”拆分为两个n=i、n=N-i-1的可行解,解即为n=i,n=N-i-1的量量组合加上”(“、”)”。当n=1时,解为‘()’;当n=0时,解为空。因此可以写成递归的解法。
利用动态规划思路,采用dp[i],存储n=i的解,可用空间换取时间,避免多次求解n=i的解。
递归解法
from itertools import product
def my_help(n):
if n < 1: return [[]]
if n == 1: return [['(',')']]
output = []
for i in range(1, 2*n, 2):
for tem_a, tem_b in list(product(my_help(i//2), my_help((2*n - i - 1)//2))):
output.append(['('] + tem_a + [')'] + tem_b)
return output
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
return [''.join(item) for item in my_help(n)]
动态规划解法
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
dp = [[] for i in range(n + 1)]
dp[0].append('')
for i in range(n + 1):
for j in range(i):
dp[i] += ['(' + x + ')' + y for x in dp[j] for y in dp[i - j - 1]]
return dp[n]