leetcode 282. 给表达式添加运算符
给定一个仅包含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)