DFS, the idea is to add and subtract direct operation, but for multiplication, to preserve the value before multiplication
For example, the input is 1322.
Assuming that we have reached 1 + 3, we would like to try 1 + 3 * 2, at this point, if the direct use of 2 * 4 will be an error, so we and 4 simultaneously passed the parameter should also have the value before the previous operation, that is, 1. When we use multiplication, we should use (4-1) * 2 + 1 as the next incoming value, while 1 is still the value of the previous operation .... In fact, I don't know what I'm talking about ... On the code.
Public classSolution {Privatelist<string> result =NewArraylist<string>(); Publiclist<string> addoperators (String num,inttarget) {Helper (num, Target,0, 0, ""); returnresult; } Public voidHelper (String num,intTargetLongValLongPre, String str) { if(val = = target && num.length () = = 0) {result.add (str); return; } intLength =num.length (); for(inti = 1; I <= length; i++) { if(i > 1 && num.charat (0) = = ' 0 ') { return; } Longleft = long.valueof (num.substring (0, i)); String Next=num.substring (i); if(str.length () = = 0) {Helper (next, Target, left,0, string.valueof (left)); } Else { //+Helper (Next, Target, Val + left, Val, str + "+" +)string.valueof (left)); //-Helper (Next, Target, Val-left, Val, str + "-" +string.valueof (left)); //*Helper (Next, Target, pre + (val-pre) * left, Pre, str + "*" +string.valueof (left)); } } }}
Expression ADD Operators