
我的代碼實(shí)現(xiàn)(Python):
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n == 0:
return []
l = []
res = []
self.a(res, l, n)
return res
def a(self, res, l, n):
if len(l) == 2 * n:
l = ''.join(l)
res.append(l)
return
if self.leftValid(l, n):
l.append('(')
self.a(res, l, n)
l.pop()
if self.rightValid(l):
l.append(')')
self.a(res, l, n)
l.pop()
def leftValid(self, l, n):
left_count = l.count('(')
if left_count == n:
return False
return True
def rightValid(self, l):
left_count = l.count('(')
right_count = l.count(')')
if left_count > right_count:
return True
return False
其實(shí)這個(gè)題很簡(jiǎn)單,用個(gè)遞歸就可以完成,不過早上寫完代碼之后一直有問題,折騰了一天,直到剛才才搞定。原來是在a函數(shù)里我本來寫了個(gè)l_copy=l,然后l給self.leftValid,l_copy給self.rightValid,然后一直搞不明白咋回事,想法沒問題啊,代碼實(shí)現(xiàn)也沒問題啊,怎么最后就只輸出一個(gè)解呢!發(fā)現(xiàn)問題的時(shí)候恍然大悟,l_copy是對(duì)l的淺拷貝,對(duì)l的操作也會(huì)引起l_copy的改變,這是問題所在!對(duì)Python使用還是不熟?。?/p>
最后看了下琨哥的代碼,比我的簡(jiǎn)潔多了!
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n==0:
return []
res = []
self.helpler(n,n,'',res)
return res
def helpler(self,l,r,item,res):
if l>r:
return
if l==0 and r==0:
res.append(item)
if l>0:
self.helpler(l-1, r, item+'(', res)
if r>0:
self.helpler(l, r-1, item+')', res)
都是遞歸,區(qū)別在于他的遞歸會(huì)生成所有的組合可能,然后判斷,如果非法即返回;而我的是先判斷,如果在加一個(gè)合法,那就加,如果非法那就不加。打個(gè)比喻,他是先進(jìn)門,看看屋里危險(xiǎn)與否,如果危險(xiǎn)那就出來;我的是現(xiàn)在門口張望,如果屋里危險(xiǎn)那就不進(jìn)了,安全才進(jìn)。
按道理講,我的算法效率應(yīng)該更高,因?yàn)槲也粫?huì)生成所有組合可能。但是執(zhí)行時(shí)間我的是70ms左右,而他的是50ms左右,我想我的代碼實(shí)現(xiàn)耗時(shí)就耗時(shí)在函數(shù)rightValid ()這,因?yàn)樗鼤?huì)計(jì)算(和)的個(gè)數(shù),且對(duì)結(jié)果的保存最開始list,最后又有個(gè)轉(zhuǎn)換。