Given a string that contains only digits 0-9
and a target value, return all possibilities to add binary operators (not unary) +
, -
, or *
between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"] "232", 8 -> ["2*3+2", "2+3*2"] "105", 5 -> ["1*0+5","10-5"] "00", 0 -> ["0+0", "0-0", "0*0"] "3456237490", 9191 -> []
Solution:
The idea is simple, just generate all the possible answers and evaluate them using dfs.
The implementation is annoying, since you need to consider some corner cases.
Code:
public class Solution {
String max = "" + Integer.MAX_VALUE;
public List<String> addOperators(String num, int target) {
List<String> ret = new ArrayList<String>();
helper(ret,num,0,"",0,0,1,target);
return ret;
}
/**
* for example 1234 ->
* suppose we have 1 + 2 + 3 * 4 and we are at 1 + 2 + 3 4 and since we do not know whether we want have
* 1 + 2 + 3 + 4 or 1 + 2 + 3 - 4 or 1 + 2 + 3 * 4,
* we need to record the value pre (1 + 2) = 3, and the value cur which is 3.
* if we assign * after the 3, the pre remains (1 + 2) = 3, and the cur is 3 * 4 = 12.
* if we assign + after the 3, the pre should be 1 + 2 + 3 = 6, and the cur is 4,
* if we assign - after the 3, the pre should be 1 + 2 + 3 = 6, the sign should be -1, and cur is 4.
*
* if(index == 0) we can only do "+"
* if charAt(index) == '0' we can only have the value 0, since we do not allow number "04".
* if the substring exceeds the value of Integer.MAX_VALUE we should break;
*
*/
void helper(List<String> ret, String num, int index,String path, int pre, int cur, int sign,int target){
int sum = pre + cur * sign;
if(index == num.length()){
if(target == sum)
ret.add(path);
return;
}
for(int i = index; i < num.length(); i++){
if(num.charAt(index) == '0' && i > index) break;
if(i - index == 9 && num.substring(index,i+1).compareTo(max) > 0) break;
int v = Integer.parseInt(num.substring(index,i+1));
if(index == 0){
helper(ret,num,i + 1, "" + v, sum, v, 1,target);
}
if(index > 0){
helper(ret,num,i + 1,path + "+" + v, sum, v, 1,target);
helper(ret,num,i + 1,path + "-" + v, sum, v, -1,target);
helper(ret,num,i + 1,path + "*" + v, pre, cur * v, sign,target);
}
}
}
}