Test case #1 and #2 failing, not sure why

#include
#include
#include
#include
using namespace std;

void checkSum(int arr[20], int index, int size, int sum, int key, int out[20], set &print)
{
if(index==size)
{
if(sum==key){
//print the array
string s;
for(int i=0; i<size; i++)
{
if(out[i]!=0)
{
s = s+to_string(out[i])+" ";
}
}
print.insert(s);
}
//as other combinations need to be search
return;
}
//include index element
if(arr[index]<=key && sum+arr[index]<=key)
{
out[index] = arr[index];
checkSum(arr, index+1, size, sum+arr[index], key, out, print);
// if(found){return true;}
//backtrack
out[index] = 0;
}
//exclude index element
checkSum(arr, index+1, size, sum, key, out, print);

}

int main() {
set print;
int num, key;
cin>>num;
int arr[20], out[20]{0};
for(int i=0; i<num; i++)
{
cin>>arr[i];
}
cin>>key;
sort(arr, arr+num);
checkSum(arr, 0, num, 0, key, out, print);
for(auto itr=print.begin(); itr!=print.end(); itr++)
{
cout<<*itr<<endl;
}
return 0;
}

hi @varun.saxena please share your code by saving it on the ide first :slight_smile:

https://ide.codingblocks.com/s/240442

hi @varun.saxena i am not quite sure what is your approach so i’ll just share mine with you
Sort the array(non-decreasing).

First remove all the duplicates from array.

Then use recursion and backtracking to solve the problem.

  1. If at any time sub-problem sum == 0 then add that array to the result (vector of vectors).

  2. Else if sum if negative then ignore that sub-problem.

  3. Else insert the present array in that index to the current vector and call the function with sum = sum-ar[index] and index = index, then pop that element from current index (backtrack) and call the function with sum = sum and index = index+1

Code: https://ide.codingblocks.com/s/240453

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.