I need to write a code using recursion
and backtracking
and without any loops that will find all possible solutions for the equation x1+x2+x3 = K
where K is a given number. and x1 , x2, x3
are non zero positive integers between 1 - 10
.
My attempt:
public static int subSetSum(int i, int k, int A[]) {
int sum = A[0] + A[1] + A[2];
int noOfSolutions = 0;
if(k - sum < 0 || i >= A.length)
return 0;
if(k - sum == 0) {
System.out.println(A[0] + " + " + A[1] + " + " + A[2]);
noOfSolutions =+ 1; }
noOfSolutions = subSetSum(i+1,k,A);
int newA[] = A;
newA[i] = A[i]+1;
noOfSolutions = subSetSum(i,k,newA);
return noOfSolutions;
}
Running the code I will only get the one solution. So If try to find all solutions for 6
it will only print out 1+1+4
and 0
(for no' of solutions).
Edit
public static int subSetSum(int i, int k, int A[]) {
int sum = A[0] + A[1] + A[2];
int noOfSolutions = 0;
if(k - sum < 0 || i >= A.length)
return 0;
if(k - sum == 0) {
System.out.println(A[0] + " + " + A[1] + " + " + A[2]);
--(1)--> noOfSolutions += 1;
--(4)--> return noOfSolutions;
}
noOfSolutions += subSetSum(i+1,k,A);
--(2)--> A[i] = A[i]+1;
noOfSolutions += subSetSum(i,k,A);
--(3)--> A[i] = A[i]-1;
return noOfSolutions;
}
Exemple
public static void main(String[] args) {
System.out.println(subSetSum(0, 4, new int[3]));
}
Output
0 + 0 + 4
0 + 1 + 3
0 + 2 + 2
0 + 3 + 1
0 + 4 + 0
1 + 0 + 3
1 + 1 + 2
1 + 2 + 1
1 + 3 + 0
2 + 0 + 2
2 + 1 + 1
2 + 2 + 0
3 + 0 + 1
3 + 1 + 0
4 + 0 + 0
15