-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path282_ExpressionAddOperators.py
More file actions
38 lines (36 loc) · 1.36 KB
/
282_ExpressionAddOperators.py
File metadata and controls
38 lines (36 loc) · 1.36 KB
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
class Solution(object):
def addOperators(self, num, target):
"""
:type num: str
:type target: int
:rtype: List[str]
"""
def isLeadingZeros(num):
return num.startswith('00') or int(num) and num.startswith('0')
def solve(num, target, mulExpr = '', mulVal = 1):
ans = []
#remove leading zeros
if isLeadingZeros(num):
pass
elif int(num) * mulVal == target:
ans += num + mulExpr,
for x in range(len(num) - 1):
lnum, rnum = num[:x+1], num[x+1:]
#remove leading zeros
if isLeadingZeros(rnum):
continue
right, rightVal = rnum + mulExpr, int(rnum) * mulVal
#op = '+'
for left in solve(lnum, target - rightVal):
ans += left + '+' + right,
#op = '-'
for left in solve(lnum, target + rightVal):
ans += left + '-' + right,
#op = '*'
for left in solve(lnum, target, '*' + right, rightVal):
ans += left,
return ans
if not num:
return []
return solve(num, target)
#reference: https://leetcode.com/discuss/58566/an-accepted-python-solution-using-dfs