[英]Appending to a list vs concatenating in python recursive calls
請看下面的leetcode問題: https://leetcode.com/problems/generate-parentheses/
在其中,您試圖生成一系列括號,其中包含一些規則,每個括號列表應該是什么樣子。
我知道兩種方法,它們在功能上似乎與我相同,但只有一種有效。 我知道 append 返回 None 並就地修改,但我看不到這如何影響遞歸過程。
這是不起作用的代碼:
class Solution:
def generate(self, output, temp, n):
if len(temp) == 2*n:
output.append(temp)
left_count = temp.count("(")
right_count = temp.count(")")
if left_count < right_count:
return
if left_count < n:
self.generate(output, temp.append("("), n)
if left_count > right_count:
self.generate(output, temp.append(")"), n)
def generateParenthesis(self, n: int) -> List[str]:
output = []
self.generate(output, ["("], n)
return output
此代碼(使用 concat)有效:
class Solution:
def generate(self, output, temp, n):
if len(temp) == 2*n:
output.append(temp)
left_count = temp.count("(")
right_count = temp.count(")")
if left_count < right_count:
return
if left_count < n:
self.generate(output, temp + "(", n)
if left_count > right_count:
self.generate(output, temp + ")", n)
def generateParenthesis(self, n: int) -> List[str]:
output = []
self.generate(output, "", n)
return output
有人可以澄清我在這里缺少什么嗎? 非常感謝。
.append
返回None
而不是所期望的附加列表。 您想先將括號添加到temp
,然后使用“更新的” temp
作為參數。
class Solution:
def generate(self, output, temp, n):
if len(temp) == 2*n:
output.append(temp)
left_count = temp.count("(")
right_count = temp.count(")")
if left_count < right_count:
return
if left_count < n:
temp.append("(") # does not return anything but modifies temp.
self.generate(output, temp, n)
if left_count > right_count:
temp.append(")") # same.
self.generate(output, temp, n)
def generateParenthesis(self, n: int) -> List[str]:
output = []
self.generate(output, ["("], n)
return output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.