Is my subsetSum function logic correct?
Hey @siddhant_samal
Ur function will always return true because it will also consider a case of empty subset which will always have sum 0
So mantain a boolean variable in arguments for that if u have picked some element or not
sir ,i have a global variable flag =0 ,for 1st time when it is zero it wouldn’t return true and for another time when the sum would get sum=0 then it would return 0…actually I am getting ans as false for a case
Dont take a global variable for this purpose , Do a dry run on some small test case if u want but i will not yield u desired results because u will get confuse which subcall is updating ur globa var
Instead pass it as an argument
sir ,i have created another code ,where i take any sum except 0 and it is giving me correct ans but for the case where sum =0 ,I am getting confused how to do ,could you share me the code
bool func(int arr[],int i,int sum,int n,bool flag)
{
if(i==n && sum==0) //reach end and sum 0
return flag==true?1:0; //flag means some element present or not
if(i==n && sum!=0)return 0; //added this
int ans1=func(arr,i+1,sum+arr[i],n,flag|true); //picking element so sending flag|true==true
int ans2=func(arr,i+1,sum,n,flag); //send flag as its as u dont know if already taken or not
return ans1||ans2;
}
i was trying this code by this DP approach but not getting what is wrong and i could do this using cumulative sum also ,So please tell me what is the issue in this https://ide.codingblocks.com/s/413048
hey @siddhant_samal
sum is 0 in this problem , u have to check whether u can have subset with 0 sum or not
so -ve m bhi sum jaayega and hence u cant do this by bottom up