Subset sum to target

question https://hack.codingblocks.com/contests/c/512/1086
my code
#include
using namespace std;

define ll long long

ll int sum=0;
bool subset( ll int a[],ll int i,ll int j,ll int k,ll int n,ll int t){

if(i==n){
return false;
}
else{

if(j<n){
            if(k<=j){
             sum +=a[k];
            
             if(sum==t){
                 
                return true;
             }
                //cout<<a[k]<<" ";
                subset(a,i,j,k+1,n,t);
               
            }
            
            else{
            // cout<<sum;
             sum=0;
                //cout<<endl;
            subset(a,i,j+1,i,n,t);
}
}
else{

subset(a,i+1,i+1,i+1,n,t);
}
}

}
int main() {
ll int t;

ll int a[1000000];
ll int n;
cin>>n;
cin>>t;
for (ll int i=0;i<n;i++){
cin>>a[i];
}

if(subset(a,0,0,0,n,t)){
    cout<<"Yes";
}
else{
   cout<<"No";
}
return 0;

}
test case 2 not passed

Hey Sarthak, can you share the online ide of your code.

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

Hey Sarthak, your code is not considering all the subsets, to correct this use either backtracking approach (i.e. to find all subsets of the array) or the dynamic programming approach for this problem.

1 Like