620. Operators to Target
A toy calculator shows a string of digits digits. A child may put +, - or * between two neighbouring digits, or put nothing there so that the digits join into a bigger number. The finished expression is read with the usual rule that multiplication happens before addition and subtraction.
Return every expression that evaluates to target. A number inside an expression may not start with 0 unless it is the single digit 0. No operator may appear before the first number. The expressions may be returned in any order. It is guaranteed that at most 150 expressions exist for each input.
Example 1
- Input:
- digits = "234", target = 10
- Output:
- ["2*3+4"]
- Explanation:
Only
2*3+4gives 10: the product 6 is computed first, then 4 is added.
Example 2
- Input:
- digits = "135", target = 8
- Output:
- ["1*3+5","13-5"]
- Explanation:
Two expressions give 8:
1*3+5and13-5(joining digits makes the number 13).
Example 3
- Input:
- digits = "99", target = 5
- Output:
- []
- Explanation:
No placement of operators between the two nines produces 5.
Constraints
- 1 ≤
digits.length≤ 8 digitscontains only decimal digits.- -109 ≤
target≤ 109 - At most 150 expressions evaluate to
target.
How this problem is judged
- Answers
- The outer list may be in any order. Everything inside each item must match exactly.
Expected complexity
- Time
- O(4^n * n)
- Space
- O(n)