leetcode 282. 給表示式新增運算子

右介發表於2018-03-29

給定一個僅包含0-9的字串和一個目標值,返回在數字之間新增了二元運算子(不是一元的) +-*之後所有能得到目標值的情況。

例如:

"123", 6 -> ["1+2+3", "1*2*3"] 
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []

#coding=utf-8
import itertools
import re

class Solution(object):
    def addOperators(self, num, target):
        if num:
            count = len(num)-1
            rnum = num[-1]

            s = "['','+','-','*'],"
            ss = ""
            for c in range(count):
                ss += s

            ls = []  
            for item in itertools.product(*eval(ss[0:-1])):
                zty = ''.join(list(itertools.chain.from_iterable(zip(list(num),item))))+rnum
                if eval(zty) != target or re.match(r".*([\+\-\*]0)\d.*",zty,re.M|re.I):
                    continue
                else:
                    ls.append(zty)
            return ls

        return []
            

print Solution().addOperators("105", 5)

 

相關文章