An iterative python solution beat about 90%


  • 0
    T
    
        def diffWaysToCompute(self, input):
            i = 0
            onenum = []
            oprs = []
            opdict = {'*':operator.mul, '-': operator.sub, '+':operator.add}
            for j, ej in enumerate(input):
                if ej in ['*', '-', '+']:
                    oprs.append(opdict[ej])
                    onenum.append([int(input[i:j])])
                    i = j+1
            onenum.append([int(input[i:])])
            N = len(onenum)
            numarr = [[], onenum]
            for cursize in range(2, N+1):
                sizeres = []
                for starti in range(N-cursize+1):
                    ares = []
                    for lsize in range(1, cursize):
                        for lval in numarr[lsize][starti]:
                            for rval in numarr[cursize-lsize][starti+lsize]:
                                ares.append(oprs[starti+lsize-1](lval, rval))
                    sizeres.append(ares)
                numarr.append(sizeres)
                
            return numarr[N][0]

Log in to reply
 

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