Problem 734
Expression Add Operators
Hard · 30 pts · String, Math, Backtracking
Problem
You are given a string of digits and a target. Insert the operators +, - or * between some of the digits (possibly none) so that the expression evaluates to the target, with the usual precedence (* before + and -). Operands may not have leading zeros, although the single digit 0 is allowed. Print the number of expressions and then each one, sorted in ASCII order. Backtrack over operand lengths, keeping the running value and the last multiplied term so that * can be undone.
Input
The first line contains the digit string NUM. The second line contains TARGET.
Output
Print the number of valid expressions, then each expression on its own line in ASCII order.
Constraints
1 <= |NUM| <= 9; -2^31 <= TARGET <= 2^31 - 1
Example input
123 6
Example output
2 1*2*3 1+2+3
Explanation
For 123 and target 6, both 1+2+3 and 1*2*3 evaluate to 6, and no other placement of operators does. In ASCII order * comes before +, so the list is 1*2*3 then 1+2+3.