Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Subset-Sum.cpp #23

Merged
merged 1 commit into from
Oct 2, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Dynamic Programming/Subset-Sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@

// Subset Sum Problem (DP)
#include <bits/stdc++.h>

using namespace std;
// Returns true if there is a subset of set[] with sun equal to given sum
bool isSubsetSum(int set[], int n, int sum){
bool subset[n+1][sum+1];
for (int i = 0; i <= n; i++)
subset[i][0] = true;
for (int i = 1; i <= sum; i++)
subset[0][i] = false;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= sum; j++){
if(j<set[i-1])
subset[i][j] = subset[i-1][j];
if (j >= set[i-1])
subset[i][j] = subset[i-1][j] || subset[i - 1][j-set[i-1]];
}
}
return subset[n][sum];
}

int main()
{
int n,sum;
//input n - size of set and sum
cin>>n>>sum;
int set[n];
//input elements of set
for(int i=0;i<n;i++)
cin>>set[i];
if (isSubsetSum(set, n, sum) == true)
cout<<"Found a subset with sum : "<<sum<<endl;
else
cout<<"No subset found with given sum : "<<sum<<endl;
return 0;
}