Expression Target Sum
In many computing contexts, from compilers to financial modeling tools, the ability to parse and evaluate mathematical expressions is fundamental. A related challenge is to reverse-engineer expressions that yield a specific target value. This problem explores how to construct such expressions from a given sequence of digits, leveraging basic arithmetic operations.
Your task is to implement a function that finds all possible valid mathematical expressions by inserting binary operators (+, -, *) between the digits of a given string num such that the expression evaluates to a target value.
addOperators which takes a string num (composed of digits '0'-'9') and an integer target.target.*) has higher precedence than addition (+) and subtraction (-).num: A string consisting only of digits ('0'-'9').target: An integer representing the desired evaluation result.string[]. A list of strings, where each string is a valid expression. The order of expressions in the output list does not matter. If no such expressions exist, return an empty list.target value can be negative.num is a single digit, say "5", and target is 5, then the output should be ["5"].Examples
Example 1
Input:
num = "123", target = 6
Output:
["1+2+3","123"]
Note:
For "123" and target 6, both "1+2+3" (1+2+3=6) and "123" (123=6) are valid expressions.
Example 2
Input:
num = "232", target = 8
Output:
["23+2","2+32"]
Note:
For "232" and target 8, "23+2" (6+2=8) and "2+32" (2+6=8) are valid expressions. Note that operator precedence is applied.
Example 3
Input:
num = "105", target = 5
Output:
["1*0+5","10-5"]
Note:
For "105" and target 5, "10+5" (0+5=5) and "10-5" (10-5=5) are valid. "105" would be invalid due to the leading zero in '05'.
Example 4
Input:
num = "00", target = 0
Output:
["0+0","0-0","0*0"]
Note:
For "00" and target 0, only single '0's can be parsed. "00" as a number is invalid. Thus, "0+0", "0-0", and "0*0" are valid.
Constraints
1 <= num.length <= 10num consists only of digits '0'-'9'.-2^31 <= target <= 2^31 - 1long in Java/C#, number in JavaScript/TypeScript).num and adhering to the 'no leading zeros' rule (unless the number is '0' itself).Loading editor...