← 返回 pinterest 的题目列表Expression Add Operators — Left-to-Right Variant (LC 282)
类型:qbank
Simplified LeetCode 282: insert `+`, `-`, `*` between digits so the resulting expression evaluates to a target — but operators apply strictly left-to-right (no precedence), so `2+3*2` evaluates as `(2+3)*2 = 10`. Asked at the Staff MLE phone screen.
Requirements
Given a digit string num and a target integer target, return every expression formed by inserting +, -, or * between adjacent digit groups that evaluates to the target. Operators apply strictly left-to-right with no precedence: 2+3*2 means (2+3)*2 = 10.
Examples
num = "123", target = 6
valid = ["1+2+3", "1*2*3"]
invalid example: "1*2+3" evaluates left-to-right to 5
Notes
Backtrack over the next digit group and operator. State is (position, accumulated_value, expression). At each step, fold the next operand directly into the accumulated value.
Reject multi-digit operands with a leading zero. With n digits, the search has O(4^n) branches before pruning: each boundary can concatenate or choose one of three operators.
The canonical precedence-aware form also tracks the previous multiplicative term; this left-to-right form does not need that bookkeeping.
Preparation
Implement the left-to-right recurrence in 20 minutes, including the leading-zero check.
Enumerate every expression for num="123" and verify each result with a tiny left-to-right evaluator.
Explain precisely why the precedence-aware form needs a previous-term state and this form does not.