-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathSubsetsum.cpp
109 lines (79 loc) · 1.43 KB
/
Subsetsum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
Name: Mehul Chaturvedi
IIT-Guwahati
*/
/*
Given a set of n integers, find if a subset of sum k can be formed from the given set. Print Yes or No.
Input Format
First line contains a single integer n (1<=n<=1000)
Second line contains n space separated integers (1<=a[i]<=1000)
Last line contains a single positive integer k (1<=k<=1000)
Output Format
Output Yes if there exists a subset whose sum is k, else output No.
Sample Input
3
1 2 3
4
Sample Output
YES
*/
#include <bits/stdc++.h>
using namespace std;
void go(vector<int> arr, int n, int i , int sum){
vector<vector<int>> dp(n+1, vector<int>(sum+1, 0));
for (int i = 0; i < n+1; ++i)
{
dp[i][0] = 1;
}
for (int i = 1; i < sum+1; ++i)
{
dp[n][i] = 0;
}
for (int j = 1; j < sum+1; ++j)
{
for (int i = n-1; i >= 0; --i)
{
bool c1 = 0;
if (j-arr[i]>=0)
{
c1 = dp[i+1][j-arr[i]];
}
if (c1 == 1)
dp[i][j] = 1;
else
{
dp[i][j] = dp[i+1][j];
}
}
}
// for (int i = 0; i < n+1; ++i)
// {
// for (int j = 0; j < sum+1; ++j)
// {
// cout<<dp[i][j]<<" ";
// }
// cout <<'\n';
// }
if (dp[0][sum] == 1)
{
cout << "Yes" << '\n';
}else
cout << "No" << '\n';
return;
}
int main( int argc , char ** argv )
{
ios_base::sync_with_stdio(false) ;
cin.tie(NULL);
int n;
cin>>n;
vector<int> arr(n, 0);
for (int i = 0; i < n; ++i)
{
cin>>arr[i];
}
int sum;
cin>>sum;
go(arr, n, 0, sum);
return 0 ;
}