-
Notifications
You must be signed in to change notification settings - Fork 43
/
subsetsum.cpp
62 lines (57 loc) · 1.22 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
// because of the complexity of the size of the array or list we are going to make the tc as 2^n
// so to avoid it we will use dp
#include <bits/stdc++.h>
using namespace std;
bool SubsetSum(int arr[], 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 < arr[i - 1])
{
subset[i][j] = subset[i - 1][j];
}
if (j >= arr[i - 1])
{
subset[i][j] = subset[i - 1][j] || subset[i - 1][j - arr[i - 1]];
}
}
}
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= sum; j++)
printf("%4d", subset[i][j]);
cout << "\n";
}
return subset[n][sum];
}
int main()
{
int n;
cin >> n;
int sum;
cin >> sum;
int *arr = new int[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
if (SubsetSum(arr, n, sum) == true)
{
cout << "Found a subset :";
}
else
{
cout << "No subset found :";
}
}