Skip to content

Commit 99775a6

Browse files
Merge pull request matthewsamuel95#79 from AnkitGuleria/subset_sum
Subset Sum problem in cpp(DP iterative Solution)
2 parents 0ceb62f + 95a7e07 commit 99775a6

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

DP/subset_sum problem/subset_sum.cpp

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
bool subset_sum(int a[],int n, int sum)
5+
{
6+
bool result[n+1][sum+1];
7+
/*result[i][j] stores yes,no corresponding to whether there is a subset of sum j in subarray a[0....i-1]*/
8+
9+
int i,j;
10+
11+
for(i=0;i<=n;i++)
12+
result[i][0]=true;/*always true for sum=0*/
13+
14+
for(j=1;j<=sum;j++)
15+
result[0][j]=false;/* case of no element corresponding to non zero sum*/
16+
17+
for(i=1;i<=n;i++)
18+
{
19+
for(j=1;j<=sum;j++)
20+
{
21+
if(result[i-1][j]==true)
22+
result[i][j]=true;
23+
24+
else
25+
{
26+
if(a[i-1]>j)
27+
result[i][j]=false;
28+
else
29+
result[i][j]=result[i-1][j-a[i-1]];
30+
31+
}
32+
}}
33+
34+
return result[n][sum];
35+
}
36+
37+
38+
39+
int main()
40+
{
41+
int i,n,sum;
42+
43+
cout<<"Enter the value of sum"<<endl;
44+
cin>>sum;
45+
46+
cout<<"Enter the number of elements in the set"<<endl;
47+
cin>>n;
48+
49+
int a[n];
50+
cout<<"Enter the values"<<endl;
51+
for(i=0;i<n;i++)
52+
cin>>a[i];
53+
54+
55+
bool answer=subset_sum(a,n,sum);
56+
57+
if(answer==true)
58+
cout<<"subset with the given sum exists";
59+
else
60+
cout<<"no required subset present";
61+
62+
cout<<endl;
63+
return 0;
64+
65+
}

0 commit comments

Comments
 (0)