When I try to get the output, it shows same solutions with same element for few times before moving on to another one.
I want to get different solutions from the array that is equal to sum
For instance,
Solution 1 = 14, 8
Solution 2 = 14, 5, 3
Solution 3 = 13, 9
and so on but what I get is repeated solutions for the sum of 22. Im getting this error
Solution : { 14, 8 }
Solution : { 14, 8 }
Solution : { 14, 8 }
Solution : { 14, 8 }
Solution : { 14, 8 }
Solution : { 14, 8 }
Solution : { 14, 5, 3 }
Solution : { 13, 6, 3 }
Solution : { 13, 5, 4 }
Solution : { 13, 5, 4 }
Solution : { 13, 6, 3 }
Solution : { 13, 5, 4 }
Solution : { 13, 5, 4 }
and another 20 lines of the same output.
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
void printSolution(int* r, int k)
{
cout << " Solution : { ";
for (int j = 0; j < k; j++)
{
cout << r[j];
if (j < k - 1)
cout << ", ";
}
cout << " }" << endl;
}
bool subSetSum(int* a, int n, int i, int sum, int* r, int k)
{
if (sum == 0)
printSolution(r, k);
if (i > n)
return false;
r[k++] = a[i];
if (subSetSum(a, n, i + 1, sum - a[i], r, k))
return true;
k -= 1;
subSetSum(a, n, i + 1, sum, r, k);
}
int descendingOrder(const void* a, const void* b)
{
int* p1 = (int*)a;
int* p2 = (int*)b;
return *p2 - *p1;
}
int main()
{
int a[] = { 4, 10, 7, 12, 6, 10, 10, 8, 5, 13, 13, 11, 3, 14 };
int n = 14;
int* r = new int[n];
int k = 0;
qsort(a, n, sizeof(int), descendingOrder);
cout << " Array a[] = ";
for (int count = 0; count < n; count++)
{
cout << a[count] << " ";
}
cout << endl << endl;
int sum = 22;
bool solFound = subSetSum(a, n, 0, sum, r, k);
return 0;
}