#282
Expression Add Operators
HardMathStringBacktrackingBacktrackingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(4^n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(4^n)Space O(n)
The optimal solution uses backtracking to explore possible expressions recursively. This method allows us to build expressions dynamically and evaluate them on-the-fly, avoiding the need to generate all combinations upfront.
⚙️
Algorithm
3 steps- 1Step 1: Use a recursive function to build expressions by adding digits and operators.
- 2Step 2: Keep track of the current value and the last operand to handle multiplication correctly.
- 3Step 3: If the end of the string is reached, check if the current value matches the target.
solution.py19 lines
1def addOperators(num, target):
2 def backtrack(index, prev_operand, current_value, expression):
3 if index == len(num):
4 if current_value == target:
5 results.append(expression)
6 return
7 for i in range(index + 1, len(num) + 1):
8 current_str = num[index:i]
9 if len(current_str) > 1 and current_str[0] == '0':
10 continue
11 current_num = int(current_str)
12 backtrack(i, current_num, current_value + current_num, expression + '+' + current_str)
13 backtrack(i, -current_num, current_value - current_num, expression + '-' + current_str)
14 backtrack(i, prev_operand * current_num, current_value - prev_operand + (prev_operand * current_num), expression + '*' + current_str)
15
16 results = []
17 for i in range(1, len(num) + 1):
18 backtrack(i, int(num[:i]), int(num[:i]), num[:i])
19 return resultsℹ
Complexity note: The time complexity is O(4^n) due to the branching factor of 4 (3 operators + 1 for no operator) at each digit position. The space complexity is O(n) for the recursion stack.
- 1Understanding operator precedence is crucial when building expressions.
- 2Backtracking is a powerful technique for exploring combinations and permutations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.