#282

Expression Add Operators

master · 1640 · lc hard +32 · verified · 42.8% accepted · 3,758 likes · top 24%

play →

Description

You are given a digit-only string num and an integer target. Insert the binary operators '+', '-', and/or '*' between digits in all possible ways and return every resulting expression that evaluates to target.

Note that operands in the returned expressions should not contain leading zeros.

Note that a number can contain multiple digits.

Example 1:

Input: num = "123", target = 6
Output: ["1*2*3","1+2+3"]
Explanation: Both "1*2*3" and "1+2+3" evaluate to 6.

Example 2:

Input: num = "232", target = 8
Output: ["2*3+2","2+3*2"]
Explanation: Both "2*3+2" and "2+3*2" evaluate to 8.

Example 3:

Input: num = "3456237490", target = 9191
Output: []
Explanation: There are no expressions that can be created from "3456237490" to evaluate to 9191.

Code

1
2
3