Python and recursion

  • 0

    Another function "pp" is used, to use recursion, and empty string s. In function "pp":

    • a,b are indices for whether the next character should be '(' or ')', respectively

    • i is index for current character

    • R stores the valid results, or solution

    • Recurse by decreasing a or b, and determine the next element in string

        class Solution(object):
            def pp(a,b,i,s,R):
            if a < 0 or a > b:
            if a == 0 and b == 0:
                if a > 0:
                    t = list(s)
                    t[i] = '('
                    s = ''.join(t)
                if b > 0:
                    t = list(s)
                    t[i] = ')'
                    s = ''.join(t)
            return R
        def generateParenthesis(self, n):
        :type n: int
        :rtype: List[str]
            s = ' '*2*n
            return Solution.pp(n,n,0,s,[])

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.