While this is a simple recursive solution, I would like to emphasize that we can use yield in Python to return multiple values with lazy manner. I believe this would be useful when a function is returning many values during its recursion.
classSolution:defrecursive_gen(self,current,opened,closed,n):ifopened==nandclosed==n:yieldcurrentelse:ifopened>closed:# can close the parentheses
yieldfromself.recursive_gen(current+')',opened,closed+1,n)ifopened+1<=n:yieldfromself.recursive_gen(current+'(',opened+1,closed,n)defgenerateParenthesis(self,n:int)->List[str]:returnlist(self.recursive_gen('',0,0,n))
This is an easy question. However, the important takeaway is that slicing string s = s[2:] is much slower than index manipulating This is because left parts of string need to be taken down by garbage collection. Otherwise, it will cause memory leak.
classSolution:defromanToInt(self,s:str)->int:symbol_value={"I":1,"IV":4,"V":5,"IX":9,"X":10,"XL":40,"L":50,"XC":90,"C":100,"CD":400,"D":500,"CM":900,"M":1000}num=0i=0whilei<len(s):c2=s[i:i+2]ifc2insymbol_value:num+=symbol_value[c2]i+=2# s = s[2:] this operation is slower than index-based method
# b/c this requires memory operations such as garbage collection
else:c1=s[i]num+=symbol_value[c1]i+=1# s = s[1:]
returnnum