-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathexpression_add_operators.py
More file actions
46 lines (36 loc) · 1.81 KB
/
Copy pathexpression_add_operators.py
File metadata and controls
46 lines (36 loc) · 1.81 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
39
40
41
42
43
44
45
46
class Solution: # Credits - LeetCode, 908ms
def addOperators(self, num: 'str', target: 'int') -> 'List[str]':
N = len(num)
answers = []
def recurse(index, prev_operand, current_operand, value, string):
# Done processing all the digits in num
if index == N:
# If the final value == target expected AND
# no operand is left unprocessed
if value == target and current_operand == 0:
answers.append("".join(string[1:]))
return
# Extending the current operand by one digit
current_operand = current_operand*10 + int(num[index])
str_op = str(current_operand)
# To avoid cases where we have 1 + 05 or 1 * 05 since 05 won't be a
# valid operand. Hence this check
if current_operand > 0:
# NO OP recursion
recurse(index + 1, prev_operand, current_operand, value, string)
# ADDITION
string.append('+'); string.append(str_op)
recurse(index + 1, current_operand, 0, value + current_operand, string)
string.pop();string.pop()
# Can subtract or multiply only if there are some previous operands
if string:
# SUBTRACTION
string.append('-'); string.append(str_op)
recurse(index + 1, -current_operand, 0, value - current_operand, string)
string.pop();string.pop()
# MULTIPLICATION
string.append('*'); string.append(str_op)
recurse(index + 1, current_operand * prev_operand, 0, value - prev_operand + (current_operand * prev_operand), string)
string.pop();string.pop()
recurse(0, 0, 0, 0, [])
return answers