|
| 1 | +# Approach 1: Backtracking |
| 2 | + |
| 3 | +# Time: O(n * 4^n) |
| 4 | + |
| 5 | +class Solution: |
| 6 | + def addOperators(self, num: str, target: int) -> List[str]: |
| 7 | + n = len(num) |
| 8 | + answers = [] |
| 9 | + |
| 10 | + def recurse(index, prev_operand, curr_operand, value, string): |
| 11 | + if index == n: |
| 12 | + # If the final value == target expected AND |
| 13 | + # no operand is left unprocessed |
| 14 | + if value == target and curr_operand == 0: |
| 15 | + answers.append(''.join(string[1:])) |
| 16 | + return |
| 17 | + |
| 18 | + # Extending the current operand by one digit |
| 19 | + curr_operand = curr_operand * 10 + int(num[index]) |
| 20 | + str_op = str(curr_operand) |
| 21 | + |
| 22 | + # To avoid cases where we have 1 + 05 or 1 * 05 |
| 23 | + if curr_operand > 0: |
| 24 | + # NO OP Recursion |
| 25 | + recurse(index + 1, prev_operand, curr_operand, value, string) |
| 26 | + |
| 27 | + # Addition |
| 28 | + string.append('+') |
| 29 | + string.append(str_op) |
| 30 | + recurse(index + 1, curr_operand, 0, value + curr_operand, string) |
| 31 | + string.pop() |
| 32 | + string.pop() |
| 33 | + |
| 34 | + # Can substract or multiply only if there are some previous operands |
| 35 | + if string: |
| 36 | + # Subtraction |
| 37 | + string.append('-') |
| 38 | + string.append(str_op) |
| 39 | + recurse(index + 1, -curr_operand, 0, value - curr_operand, string) |
| 40 | + string.pop() |
| 41 | + string.pop() |
| 42 | + |
| 43 | + # Multiplication |
| 44 | + string.append('*') |
| 45 | + string.append(str_op) |
| 46 | + recurse(index + 1, curr_operand * prev_operand, 0, value - prev_operand + (curr_operand * prev_operand), string) |
| 47 | + string.pop() |
| 48 | + string.pop() |
| 49 | + |
| 50 | + recurse(0, 0, 0, 0, []) |
| 51 | + return answers |
| 52 | + |
0 commit comments