i need to find an algorithm that use a recursive backtracking algorithm which will print me all the possible compositions to x1+x2+x3 to be equals to the number.
lets say the input number is 4 so the method will print me 3 results:
1 1 2
1 2 1
1 1 2
...... The code:
public class getResult
public static void results(int n)
{
int[] history= new int[3];
results(n,history,0);
}
private static void results(int n,int[] history,int i)
{
if(n==0)
{
printHistory(history,0,i);
System.out.println();
}
if`(n>0&&i<3)`
{
history[i]=1;
//insert 1 to history in order to go back in case of wrong
// way using backtracking.
results(n-1,history,i+1);//calling the function again, with n-1 , backup history, history[i+1]`
history[i]=2;
results(n-2,history,i+1);
history[i]=3;
results(n-3,history,i+1);
//.....9
}
}
private static void printHistory(int[] history,int from,int to)
{
if(from<to)
{
System.out.print(history[from]+"\t");
printHistory(history,from+1,to);
}
}
}
I have 2 questions:
1. how can I print only the results that concludes x1,x2,x3.
Because for now, if i try to input num=5 it will print me the following results:
1 1 3
1 2 2
1 3 1
1 4
2 1 2
2 2 1
2 3
3 1 1
3 2
4 1
5
And i want to get the results that only conclude 3 numbers(without for example the results: 5, 4 1, 3 2, 2 3)..
2.Is there a way to write these lines better:
history[i]=1;
results(n-1,history,i+1)`;`
instead every time to copy the code and subtract a number manually from the number?(The results should pass all over the numbers between 1 to 9)
Thank you all for help, if something isn't clear i would like to help :)
n == 0 && i == 3instead ofn==0where you print the result