Problem 548389 · hard · Phase 05 Advanced Algorithms & Graphs

Count Formulas Hitting a Target

backtracking · expression evaluation · operator precedence · counting

A calculator toy shows a row of digits digits. Between each pair of neighbouring digits you may put +, -, *, or nothing (which glues the digits into a longer number). A multi-digit number may not start with 0. Multiplication binds tighter than addition and subtraction, as usual. Count how many different formulas evaluate to exactly target.

Examples

Input:  digits = "232", target = 8
Output: 2
Explanation: 2*3+2 and 2+3*2.

Input:  digits = "10", target = 1
Output: 2
Explanation: 1+0 and 1-0.

Input:  digits = "05", target = 5
Output: 1
Explanation: 0+5 works, "05" is not allowed as a number.

Constraints

  • 1 <= len(digits) <= 9, -10**9 <= target <= 10**9

Goals

  • Enumerate operator placements while evaluating incrementally
  • Handle multiplication precedence by tracking the last term
Starting Python…