Question: Mike is a very passionate about sets. Lately, he is busy solving one of the problems on sets. He has to find whether if the sum of any of the non-empty subsets of the set A is zero.If the sum of any of the subset is zero, then print “Yes” (without quotes) else print “No”(without quotes).
I am having problem in implementation of recursive approach-- Please explain how to proceed.
I have tried my code but it is giving wrong answer. Please point out my mistake and please suggest ways how to think and proceed with such recursive problems
#include
using namespace std;
bool subsetsum(int*,int*,int,int,int);
int main() {
int t,n;
cin>>t;
while(t–)
{
cin>>n;
int* arr=new int[n];
int* oarr=new int[n];//to store the subset elements
for(int i=0;i<n;i++)
cin>>arr[i];
bool res=subsetsum(arr,oarr,0,0,n);
if(res==true)
cout<<“No”;
else
cout<<“Yes”;
}
return 0;
}
bool subsetsum(int* arr,int* oarr,int i,int j,int n)
{
if(i==n)//when i pointer reaches the last element return true ie No
{
int ans=0;
for(int k=0;k<j;k++)
ans=ans+oarr[k];
if(ans==0)
return false;
else
return true;
}
int ans=0;
for(int k=0;k<j;k++)
ans=ans+oarr[k];
if(j!=0 && ans==0){
return false;
}//when sum is 0 return false ie Yes
oarr[j]=arr[i];
subsetsum(arr,oarr,i+1,j+1,n);//when subset sum includes the current element
subsetsum(arr,oarr,i+1,j,n);//when subset sum excludes the current element
}