I am writing a program to find if a given sum is possible from a subset of an array. (Subset sum problem). Although many implementations are available on the internet, I have chosen to code it myself. please suggest appropriate corrections. I am doing this using dynamic programming.
#include<iostream>
using namespace std;
bool subsetsum(int a[],int n,int s){
bool T[n][s];
for(int j=0;j<n;j++){
T[j][0]=true;
}
for(int k=1;k<n;k++){
T[0][k]=false;
for(int l=1;l<n;l++){
if((a[k]<s) && ((subsetsum(a,n-1,s-a[k])) || (subsetsum(a,n-1,s)))){
T[k][l]=true;
}
else{
T[k][l]=false;
}
}
}
return T[n][s];
}
int main(){
int n,s;
int a[n];
cout<<"Enter number of elements:\n";
cin>>n;
cout<<"Enter sum required\n";
cin>>s;
cout<<"Enter elements:\n";
for(int i=0;i<n;i++){
cin>>a[i];
}
cout<<subsetsum(a,n,s);
}
The output I obtained is below:
Enter number of elements:
3
Enter sum required
5
Enter elements:
1
4
2
0
I do not understand why I obtained 0 as the result when boolean should have been returned.