-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathExpression Add Operators.py
54 lines (54 loc) · 1.52 KB
/
Expression Add Operators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
s=num[0]
q=["+","-","*",""]
ans=[]
def cal(w):
i=1
while i<len(w)-1:
if w[i]=='*':
q=int(w[i-1])*int(w[i+1])
del w[i+1]
del w[i]
w[i-1]=q
continue
i+=2
i=1
while i<len(w)-1:
if w[i]=='+':
q=int(w[i-1])+int(w[i+1])
del w[i+1]
del w[i]
w[i-1]=q
continue
elif w[i]=='-':
q=int(w[i-1])-int(w[i+1])
del w[i+1]
del w[i]
w[i-1]=q
continue
i+=2
return w
def dfs(s,i):
nonlocal ans
if i==len(num):
x=''
myl=[]
for i in s:
if i not in ['+','-','*']:
x+=i
else:
myl.append(int(x))
myl.append(i)
x=''
myl.append(int(x))
print(myl)
a=cal(myl)
print(a)
if a[0]==target:
ans.append(s)
return
for j in q:
dfs(s+j+num[i],i+1)
dfs(s,1)
return ans