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
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:
Note
overflow: we use a long type once it is larger than Integer.MAX_VALUE or minimum, we get over it.
0 sequence: because we can't have numbers with multiple digits started with zero, we have to deal with it too
a little trick is that we should save the value that is to be multiplied in the next recursion.
存之前的值,对于1 + 23,在2和3之间加入”*“,1+2+2*3-2,需要减掉之前保存的值来维持运算的优先级。
对于0,剪枝的原则:起始零,如01,00,02等情况,需要容忍单个0的情况。i != start && num.charAt(start) == '0'
初始化时start为0,加入当前的值,不做运算操作
Code
Last updated