282. Expression Add Operators

Given a string that contains only digits0-9and a target value, return all possibilities to add binary operators (not unary)+,-, or*between the digits so they evaluate to the target value.

Example 1:

Input:
num = "123", 
target= 6

Output: ["1+2+3", "1*2*3"]

Example 2:

Input:
num = "232", 
target = 8

Output: ["2*3+2", "2+3*2"]

Example 3:

Input:
num = "105", 
target = 5

Output: ["1*0+5","10-5"]

Example 4:

Example 5:

Thoughts:

  1. DFS: expanding each level:

    1. from curDepth to the end of the string, first extract the operand:

    2. if num[curDepth] == '0', stop further expanding since we do not want a number with leading 0's

    3. if current level is 0, then expanding it as the first operator

    4. otherwise: expanding by appending the ['+', '-', '*'] at the end

Code

Last updated

Was this helpful?