I am trying to solve this arithmetic expression problem where I take n (here 5) elements in an array and try all combination of operators in (+ - *) to find if the expression is divisible by 101 Here, we are not concerned with order of operators..not using BODMAS Input
5
55 3 45 33 25
Output
55+3-45*33-25
I am new at recursion and backtracking. I am trying to understand which part of the problem is wrong
Here's my code:
public static boolean solve(char []operators,long[]nums,long res,int index,Stack<Character>st){
if(index+1==nums.length){ //reached end of number array
if(res%101==0){
System.out.println(res);
return true;
}
return false;
}
for(int i=0;i<operators.length;i++){
char op=operators[i]; //try the operator
long num1=nums[index];
long num2=nums[index+1]; //LINE1
System.out.println("trying "+num1+""+op+" num2="+num2);
res=performOp(op,num1,num2);
nums[index+1]=res;
st.push(op);
if(solve(operators,nums,res,index+1,st)){
return true;
}
//backtrack
//return to earlier state than try another operator
//LINE2
nums[index+1]=performBackTrack(op,num1,num2); //restoring number
System.out.println("num2="+num2+" num1="+num1+" after backtrack");
st.pop();
}
return false;
}
public static long performBackTrack(char op,long num1,long num2){
//trying to restore numbers
switch(op){
case '+':return num2-num1;
case '-':return num1-num2;
case '*':return num1/num2;
default:return 0L;
}
}
public static long performOp(char op,long num1,long num2){
switch(op){
case '+':return num1+num2;
case '-':return num1-num2;
case '*':return num1*num2;
default:return 0L;
}
}
Here after backtracking, when I make changes at LINE2 and go inside the loop to try next operator, the change works fine as I get back the orignal number at LINE2 but it is not reflected at LINE1, the last number I try to restore before trying an operator is not reflected at LINE1.
Please help..Any kind of help will be appreciated ...