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:
[ "((()))", "(()())", "(())()", "()(())", "()()()"]
題目思路:
①不難發(fā)現(xiàn),n為0的時(shí)候輸出是空,而n = 1的時(shí)候,輸出“()”
②當(dāng)n > 1的時(shí)候,要使得整個(gè)括號(hào)字符串可以配對(duì),那么與第一個(gè)配對(duì)的右括號(hào)把n - 1對(duì)括號(hào)分成了一個(gè) i (0 <= i < n)對(duì)已配對(duì)的括號(hào)和 n - 1 - i對(duì)已配對(duì)的括號(hào)。那么把所有的右括號(hào)劃分的情況全部列出來(lái)就可以了。由于這里的時(shí)間復(fù)雜度比較復(fù)雜,就不作分析了。
根據(jù)上述可以得到:
f(n) = ∑( '(' + f(i) +')' + f(n - 1 - i) )
class Solution(object):
"""
:type n: int
:rtype: List[str]
"""
def generateParenthesis(self, n):
result = []
def func(left,right,s):
if left < right :
return
if (left+right == n*2):
if (left == right):
result.append(s)
return
func(left,right+1,s+')')
func(left+1,right,s+'(')
func(1,0,'(')
return result
遞歸解法,左括號(hào)的個(gè)數(shù)比右括號(hào)多
class Solution(object):
"""
:type n: int
:rtype: List[str]
"""
def generateParenthesis(self, n):
result = []
def func(left,right,s):
if left < right :
return
if (left+right == n*2):
if (left == right):
result.append(s)
return
func(left,right+1,s+')')
func(left+1,right,s+'(')
func(1,0,'(')
return result