Skip to content

Expression Add Operators

HardBacktracking
Decode it first. Clues, constraints, pattern and plan before any code.

Given a string of digits num and an integer target, insert the operators +, - or * between digits (or nothing, which joins digits into a longer number) so that the expression evaluates to target using normal precedence (* before + and -). Return all expressions that work, in any order. Numbers in the expression may not have leading zeros (05 is not allowed, 0 is).

num = "123", target = 6  →  ["1+2+3", "1*2*3"]
num = "232", target = 8  →  ["2*3+2", "2+3*2"]
num = "105", target = 5  →  ["1*0+5", "10-5"]

Constraints

  • 1 <= num.length <= 10
  • num consists of only digits.
  • -2^31 <= target <= 2^31 - 1