![]() |
VOOZH | about |
Given a string digits containing only digits (0-9) and an integer target, find all possible expressions that evaluate to the target value using the binary operators +, -, and *. If no such expression is possible, return an empty list.
Input : digits = "124", target = 9
Output : [“1+2*4”]
Explanation: The valid expressions that evaluate to 9 are (1 + 2 * 4).Input : digits = “125”, target = 7
Output : [“1*2+5”, “12-5”]
Explanation: The two valid expressions that evaluate to 7 are (1 * 2 + 5) and (12 - 5).
We can generate all expressions by inserting the operators +, -, and * between the digits recursively. At each recursion step:
Multiplication Handling:
This adjustment ensures that 1 + 2*5 is evaluated correctly as 1 + (2*5) rather than (1 + 2)*5.
1+2*4
Time Complexity: O(4n), because at each of the n-1 positions between digits we can insert one of three operators +, -, * or choose no operator (concatenate digits), generating all possible expressions.
Auxiliary Space: O(n), for the recursion stack and the current expression being built;