class Solution:
def generateParenthesis(self, n: int) -> List[str]:
ans = []
def backtrack(S, left, right):
if len(S) == 2 * n:
ans.append(''.join(S))
return
if left < n:
S.append('(')
backtrack(S, left+1, right)
S.pop()
if right < left:
S.append(')')
backtrack(S, left, right+1)
S.pop()
backtrack([], 0, 0)
return ans
I am new to algorithms, and this is leetcode #22.
I don't understand why S.pop()
is needed in the last line of the function here?
I think when I backtrack to the previous function, the value S
will be the value in the previous function, so there is no need to write S.pop()
at the end of this function?
as it only changes value of S
in this function, not in the previous one?
But in practice, when I returned to the previous function, the change in S
's value still
remains? But I thought when I enter a new function a new local copy should be created? So is S
's value shared in all generateParenthesis
function?