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:
Recursively add operator and check the result till so far.
The difficult point is add "*", I use sum to keep track the summation before we add multiply and use number to track the product.
If we are going to try "+", we can assign the sum=sum+nextNumber, and number=1, because '+' and '-' have lower priority than '*'. But if we are going to try '*', we have to keep previous sum and keep calculating product.
Also we need to take care of 0. If current number is 0, we break the iteration, and directly try next recursion, because '00','01'...is not a valid number.
Recursively add operator and check the result till so far.
The difficult point is add "*", I use sum to keep track the summation before we add multiply and use number to track the product.
If we are going to try "+", we can assign the sum=sum+nextNumber, and number=1, because '+' and '-' have lower priority than '*'. But if we are going to try '*', we have to keep previous sum and keep calculating product.
Also we need to take care of 0. If current number is 0, we break the iteration, and directly try next recursion, because '00','01'...is not a valid number.
public List<String> addOperators(String num, int target) {
List<String> res=new ArrayList<String>();
helper(num,0,0,1,target,"",res);
return res;
}
public void helper(String num, int ind, long sum, long number, int target,String item,List<String> res){
if(ind==num.length()){
if(sum==target) res.add(item);
return;
}
for(int i=ind+1;i<=num.length();i++){
long temp=Long.parseLong(num.substring(ind,i));
long nextNumber= temp*number;
if(i==num.length()){
helper(num,i,sum+nextNumber,0,target,item+temp,res);
}
else{
helper(num,i,sum+nextNumber,1,target,item+temp+"+",res);
helper(num,i,sum+nextNumber,-1,target,item+temp+"-",res);
helper(num,i,sum,nextNumber,target,item+temp+"*",res);
}
if(num.charAt(ind)=='0') break;
}
}
No comments:
Post a Comment