-
Notifications
You must be signed in to change notification settings - Fork 1
/
expression-add-operators.py
37 lines (32 loc) · 1.06 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
class Solution(object):
def addOperators(self, num, target):
"""
:type num: str
:type target: int
:rtype: List[str]
"""
res = []
def helper(num, path, val, multed):
# print(num, path, val)
if num == "":
if target == val:
res.append(path)
for i in range(1, len(num)+1):
n = int(num[:i])
# if str(int(num[:i])) != num[:i]:
# break
if i != 1 and num[:i][0] == "0":
break
if path == "":
helper(num[i:], path + num[:i], n, n)
else:
helper(num[i:], path + "+" + num[:i], val + n, n)
helper(num[i:], path + "-" + num[:i], val - n, -n)
helper(num[i:], path + "*" + num[:i], val - multed + multed * n, multed * n)
helper(num, "", 0, 0)
return res
num = "105"
target = 5
#expect ["1*0+5", "10-5"]
r = Solution().addOperators(num, target)
print(r)